如何过滤dict以仅包含给定列表中的键?

时间:2011-07-26 09:17:29

标签: python list dictionary filter

对Python和stackoverflow都很新。感谢您的耐心和帮助。

我想根据列表的内容过滤dict:

d={'d1':1, 'd2':2, 'd3':3}

f = ['d1', 'd3']

r = {items of d where the key is in f}
这是荒谬的吗? 如果没有,那么正确的语法是什么?

感谢您的帮助。

文森特

2 个答案:

答案 0 :(得分:15)

假设您要创建新词典(无论出于何种原因):

d = {'d1':1, 'd2':2, 'd3':3}
keys = ['d1', 'd3']

filtered_d = dict((k, d[k]) for k in keys if k in d)
# or: filtered_d = dict((k, d[k]) for k in keys)
# if every key in the list exists in the dictionary

答案 1 :(得分:3)

您可以使用列表推导迭代列表,并在字典中查找键,例如

aa = [d[k] for k in f]

这是一个有效的例子。

>>> d = {'k1': 1, 'k2': 2, 'k3' :3}
>>> f = ['k1', 'k2']
>>> aa = [d[k] for k in f]
>>> aa
[1, 2]

如果要从结果中重建字典,可以在元组列表中捕获键并转换为字典,例如。

aa = dict ([(k, d[k]) for k in f])

更新版本的Python(特别是2.7,3)有一个名为dict comprehension的功能,它将在一次点击中完成所有操作。深入讨论here.

相关问题