我想合并字典中的所有字典,同时忽略主字典键,并按值汇总其他字典的值.
输入:
{'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}}
输出:
{'a': 15, 'b': 5, 'c': 1}
我做了:
def merge_dicts(large_dictionary):
result = {}
for name, dictionary in large_dictionary.items():
for key, value in dictionary.items():
if key not in result:
result[key] = value
else:
result[key] += value
return result
哪个有效,但我不认为这是一个好方法(或更少“pythonic”).
顺便说一句,我不喜欢我写的标题.如果有人想到更好的措辞,请编辑.