Python-根据选择列表中的值过滤字典键
有时在Python字典中,我们可能需要根据某些条件过滤掉字典中的某些键。在本文中,我们将看到如何从Python字典中过滤掉键。
与for和in
在这种方法中,我们将要过滤的键的值放在列表中。然后遍历列表的每个元素,并检查其在给定字典中的存在。我们创建一个包含这些值的结果字典,这些值可以在字典中找到。
示例
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']热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短