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

Python通过求和值将字典的字典合并为一个字典,python,python-3.x,dictionary,merge,add,Python,Python 3.x,Dictionary,Merge,Add,我希望将所有字典合并到一个字典中,同时忽略主字典键,并按值对其他字典的值求和 输入: {'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():

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

输入:

{'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”)


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

您可以对计数器求和,它是dict子类:

>>> 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))

你做的唯一不好的事情是检查
large\u dictionary.items()
而不是
large\u dictionary.values()
。我没有把列表放在defaultdict中,我把defaultdict(lambda:0)、defaultdict(int)和defaultdict(lambda:0)的结果放在了相同的位置。但是int会更像python,我还想。@wim-Oh。嗯,我想它总是会返回相同的列表。但事实并非如此。等我有更多时间的时候再好好想想。谢谢你的更正。@wim是的,好吧,我是个白痴。。。不会期望
def():return[]
总是返回相同的值。关于
defaultdict(lambda:[])
的一些东西不知怎么把我甩了。我猜是因为它看起来太像参数默认符号。