Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 323
sheldonzy Avatar asked Jan 29 '23 07:01

sheldonzy


1 Answers

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})
like image 67
wim Avatar answered Feb 05 '23 17:02

wim