Python通过对值进行求和将字典词典合并为一个字典

she*_*nzy 4 python merge dictionary add python-3.x

我想合并字典中的所有字典,同时忽略主字典键,并按值汇总其他字典的值.

输入:

{'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}}
Run Code Online (Sandbox Code Playgroud)

输出:

{'a': 15, 'b': 5, 'c': 1}
Run Code Online (Sandbox Code Playgroud)

我做了:

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
Run Code Online (Sandbox Code Playgroud)

哪个有效,但我不认为这是一个好方法(或更少"pythonic").

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

wim*_*wim 6

你可以对计数器进行求和,这是一个dict子类:

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