我正在尝试用相同的键来汇总一些字典以创建总和。我在这里找到了2个词典的解决方案:
How to merge two Python dictionaries in a single expression?
如何扩展此功能以考虑N个字典链?
dictionary = {1:{'a':4,'b':10},0:{'a':2,'b':55}, ... N:{'a':10,'b':11}}
for k, v in itertools.chain(dictionary[0].items(), dictionary[1].items() ...):
c[k] += v
答案 0 :(得分:3)
更好的方法:
from collections import Counter
totals = Counter()
for dct in dictionary.values():
totals.update(dct)