我有一个包含许多词典的大型列表。在每个字典中,我想迭代3个特定键,然后转储到新列表中。每个字典的键都相同。
例如,我想从下面列表中的所有词组中获取键c,d,e,输出到List2。
List = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6...},
{'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60...},
{'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600...},]
List2 = [{'c':3, 'd':4, 'e':5},
{'c':30, 'd':40, 'e':50},
{'c':300, 'd':400, 'e':500}]
答案 0 :(得分:6)
您可以使用嵌套的字典理解:
keys = ('c', 'd', 'e')
[{k: d[k] for k in keys} for d in List]
如果缺少 这些键,您可以使用dictionary view object(Python 2中的dict.viewkeys()
,Python 3中的dict.keys()
)来查找交叉点仅包括实际存在的密钥:
keys = {'c', 'd', 'e'}
[{k: d[k] for k in d.viewkeys() & keys} for d in List]
演示:
>>> List = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6},
... {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60},
... {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600}]
>>> keys = ('c', 'd', 'e')
>>> [{k: d[k] for k in keys} for d in List]
[{'c': 3, 'e': 5, 'd': 4}, {'c': 30, 'e': 50, 'd': 40}, {'c': 300, 'e': 500, 'd': 400}]
>>> List = [{'a':1, 'b':2, 'd':4, 'e':5, 'f':6},
... {'a':10, 'b':20, 'c':30, 'd':40, 'f':60},
... {'a':100, 'b':200, 'e':500, 'f':600}]
>>> keys = {'c', 'd', 'e'}
>>> [{k: d[k] for k in d.viewkeys() & keys} for d in List]
[{'e': 5, 'd': 4}, {'c': 30, 'd': 40}, {'e': 500}]
答案 1 :(得分:1)
试试这段代码:
keys = ['c', 'd']
for dictionary in List1:
d = {}
for key in dictionary:
if key in keys:
d[key] = dictionary[key]
List2.append(d)