Python combines a dictionary of dictionaries into a single dictionary, summing up the value

I want to combine all the dictionaries in the dictionary, ignoring the main dictionary keys and summing up the meaning of other dictionaries by value.

Input:

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

Conclusion:

{'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 this is such a good way (or less "pythonic").

By the way, I do not like the title that I wrote. If anyone thinks of a better wording, edit it.

+4
source share
3 answers

You can summarize the counters, which are a subclass of dict:

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

It 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))
+2
source

Almost similar, but it's just short, and I feel 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
0
source

Source: https://habr.com/ru/post/1688701/


All Articles