我必须合并python字典的列表。例如:
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)
它能被更优雅地呈现/优化吗?
我在上面找到了另一个question,但是它是关于合并2个字典的。
发布于 2012-02-23 23:29:43
您可以直接迭代字典--不需要使用range
。dict的setdefault
方法查找一个键,如果找到则返回值。如果未找到,它将返回默认值,并将该默认值分配给键。
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
。
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
会满足您的需求:
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)
发布于 2012-02-23 23:33:54
from collections import defaultdict
dicts = [{'a':1, 'b':2, 'c':3},
{'a':1, 'd':2, 'c':'foo'},
{'e':57, 'c':3} ]
super_dict = defaultdict(set) # uses set to avoid duplicates
for d in dicts:
for k, v in d.items(): # use d.iteritems() in python 2
super_dict[k].add(v)
发布于 2019-08-30 22:06:54
你可以使用dict的这种行为。(有点优雅)
a = {'a':1, 'b':2, 'c':3}
b = {'d':1, 'e':2, 'f':3}
c = {1:1, 2:2, 3:3}
merge = {**a, **b, **c}
print(merge) # {'a': 1, 'b': 2, 'c': 3, 'd': 1, 'e': 2, 'f': 3, 1: 1, 2: 2, 3: 3}
现在就可以开始了:)
https://stackoverflow.com/questions/9415785
复制相似问题