Python 从键列表中筛选字典
我想根据一组/列表/(dict)键筛选字典 目前我使用的发电机如下:Python 从键列表中筛选字典,python,list,loops,dictionary,generator,Python,List,Loops,Dictionary,Generator,我想根据一组/列表/(dict)键筛选字典 目前我使用的发电机如下: def filter_dict(in_dict, in_iterator): for key, value in in_dict.items(): if key in in_iterator: yield key, value d = {'one': 1, 'two': 2, 'three': 3} l = ['one', 'two'] for key, value in
def filter_dict(in_dict, in_iterator):
for key, value in in_dict.items():
if key in in_iterator:
yield key, value
d = {'one': 1, 'two': 2, 'three': 3}
l = ['one', 'two']
for key, value in filter_dict(d, l):
print(key, value)
它工作良好,过滤正确,结果如下:
one 1
two 2
是否有更好或更标准的方法来做到这一点
可能类似于
filter(d,l)
或d.items(l)
一种可能是对dict.keys()执行设置操作:
印刷品:
one 1
two 2
您可以简单地遍历列表,从dict中选择项目并创建一个新dict,而不是遍历所有键,然后检查它是否存在于另一个列表中
new_dict = dict( ((key, d[key]) for key in l) )
如果列表中的项目不在词典中,则使用此选项时会出现错误:
完成它大约需要5秒钟
new_dict = dict(((key, d[key]) for key in l))
您可以使用以下内容:
def filter_dict(in_dict, in_iterator):
for key, value in in_dict.items():
if key in in_iterator:
yield key, value
d = {'one': 1, 'two': 2, 'three': 3}
l = ['one', 'two']
for key, value in filter_dict(d, l):
print(key, value)
如果列表中的项目不在词典中,您可以确保不会出现错误
keys = set(l).intersection(d)
result = {key:d[key] for key in keys}
但是它大约需要17秒,而且性能不好
您可以使用此功能,完成此功能大约需要5秒钟,您可以确保不会出现任何错误:
是的,你说得对。在这种情况下,生成器应该遍历列表并返回dict项(如果它们存在的话)。或者只使用字典理解:{k:d[k]表示l中的k}
。这避免了元组的生成器表达式/显式构造。在上面的示例中,对于key,value in{k:d[k]对于k in l}。items()
如果l
包含不存在的key,这两个示例都会出错d
great!这是一个很好的解决方案。但我们可能会失去一点可读性?非常感谢您的回答和时间比较。你的建议是根据这个问题提出的吗<代码>用于集合(d)中的键。交叉点(l):
result = {}
for k in set(d1).intersection(l1):
result[k]= d1[k]