【发布时间】:2020-04-08 03:16:18
【问题描述】:
我想根据键的集合/列表/(字典)过滤字典。
目前我正在使用这样的生成器:
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)
【问题讨论】:
标签: python list loops dictionary generator