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']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP