合并几个python字典 [英] merging several python dictionaries
问题描述
我必须合并python词典列表.例如:
I have to merge list of python dictionary. For eg:
dicts[0] = {'a':1, 'b':2, 'c':3}
dicts[1] = {'a':1, 'd':2, 'c':'foo'}
dicts[2] = {'e':57,'c':3}
super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]}
我编写了以下代码:
super_dict = {}
for d in dicts:
for k, v in d.items():
if super_dict.get(k) is None:
super_dict[k] = []
if v not in super_dict.get(k):
super_dict[k].append(v)
可以更优雅地展示/优化吗?
注意 我在SO上发现了另一个问题,但它恰好是合并了2个字典.
Note I found another question on SO but its about merging exactly 2 dictionaries.
推荐答案
您可以直接迭代字典-无需使用range
. dict的setdefault
方法查找键,如果找到,则返回值.如果找不到,它将返回默认值,并将该默认值分配给密钥.
You can iterate over the dictionaries directly -- no need to use range
. The setdefault
method of dict looks up a key, and returns the value if found. If not found, it returns a default, and also assigns that default to the key.
super_dict = {}
for d in dicts:
for k, v in d.iteritems(): # d.items() in Python 3+
super_dict.setdefault(k, []).append(v)
此外,您可以考虑使用defaultdict
.这通过调用一个函数来自动setdefault
,以在找不到键时返回默认值.
Also, you might consider using a defaultdict
. This just automates setdefault
by calling a function to return a default value when a key isn't found.
import collections
super_dict = collections.defaultdict(list)
for d in dicts:
for k, v in d.iteritems(): # d.items() in Python 3+
super_dict[k].append(v)
此外,正如 Sven Marnach 所观察到的那样,您似乎不希望列表中的值重复.在这种情况下,set
为您提供想要的东西:
Also, as Sven Marnach astutely observed, you seem to want no duplication of values in your lists. In that case, set
gets you what you want:
import collections
super_dict = collections.defaultdict(set)
for d in dicts:
for k, v in d.iteritems(): # d.items() in Python 3+
super_dict[k].add(v)
这篇关于合并几个python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!