Python 通过对值求和将字典的字典合并为一个字典

Python merging dictionary of dictionaries into one dictionary by summing the value

我想合并一个字典中的所有字典,同时忽略主字典键,并按值对其他字典的值求和。

输入:

{'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")。

顺便说一句,我不喜欢我写的标题。如果有人想到更好的措辞,请编辑。

您可以对作为字典子类的计数器求和:

>>> from collections import Counter
>>> sum(map(Counter, d.values()), Counter())
Counter({'a': 15, 'b': 5, 'c': 1})

差不多,只是比较短,我比较喜欢

def merge_dicts(large_dictionary):
    result = {}
    for d in large_dictionary.values():
        for key, value in d.items():
            result[key] = result.get(key, 0) + value
    return result

这会起作用

from collections import defaultdict
values = defaultdict(int)
def combine(d, values):
    for k, v in d.items():
        values[k] += v

for v in a.values():
    combine(v, values)

print(dict(values))