有时在Python字典中,我们可能需要根据某些条件过滤掉字典中的某些键。在本文中,我们将看到如何从Python字典中过滤掉键。
在这种方法中,我们将要过滤的键的值放在列表中。然后遍历列表的每个元素,并检查其在给定字典中的存在。我们创建一个包含这些值的结果字典,这些值可以在字典中找到。
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']
print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
res = [dictA[i] for i in key_list if i in dictA]
print("Dictionary with filtered keys:\n",res)输出结果
运行上面的代码给我们以下结果-
Given Dictionary:
{'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
['Tue', 'Thu']
Dictionary with filtered keys:
['chem', 'Bio']我们使用交集找到给定字典和列表之间的共同元素。然后应用set函数获得不同的元素,并将结果转换为列表。
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']
print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
temp = list(set(key_list).intersection(dictA))
res = [dictA[i] for i in temp]
print("Dictionary with filtered keys:\n",res)输出结果
运行上面的代码给我们以下结果-
Given Dictionary:
{'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
['Tue', 'Thu']
Dictionary with filtered keys:
['chem', 'Bio']