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

戏子无情 提交于 2019-12-04 03:47:49

问题


I want to merge all the dictionaries in a dictionary, while ignoring the main dictionary keys, and summing the value of the other dictionaries by value.

Input:

{'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}}

Output:

{'a': 15, 'b': 5, 'c': 1}

I did:

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

Which works, but I don't think it's such a good way (or less "pythonic").

By the way, I don't like the title I wrote. If anybody thinks of a better wording please edit.


回答1:


You can sum counters, which are a dict subclass:

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



回答2:


This will work

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



回答3:


Almost similar, but it's just short and I like it a little better.

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


来源:https://stackoverflow.com/questions/47101947/python-merging-dictionary-of-dictionaries-into-one-dictionary-by-summing-the-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!