从键列表中过滤字典

时间:2019-12-15 11:24:33

标签: python list loops dictionary generator

我想根据一组键/列表/(字典)来过滤字典。

目前,我正在使用这样的生成器:

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)

3 个答案:

答案 0 :(得分:1)

您无需遍历所有键然后检查它是否存在于另一个列表中,而只需浏览列表并从dict中选择项目并创建一个新的dict。

new_dict = dict( ((key, d[key]) for key in l) )

答案 1 :(得分:0)

一种可能性是对dict.keys()进行设置操作:

d = {'one': 1, 'two': 2, 'three': 3}
l = ['one', 'two']

for k in d.keys() & set(l):
    print(k, d[k])

打印:

one 1
two 2

答案 2 :(得分:0)

如果列表中的项目不在词典中,则使用此错误:
完成大约需要5秒

new_dict = dict(((key, d[key]) for key in l))

您可以使用以下内容:

如果您列表中的项目不在字典中,则可以确保不会收到错误消息

keys = set(l).intersection(d)
result = {key:d[key] for key in keys}

,但是大约需要17秒,而且效果也不佳

您可以使用它,大约需要5秒钟才能完成它,并且可以确保不会出现任何错误:  

result = {}
for k in set(d1).intersection(l1):
    result[k]= d1[k]