How to sum dict elements

Nazmul Hasan picture Nazmul Hasan · Aug 16, 2010 · Viewed 57.1k times · Source

In Python, I have list of dicts:

dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}]

I want one final dict that will contain the sum of all dicts. I.e the result will be: {'a':5, 'b':7}

N.B: every dict in the list will contain same number of key, value pairs.

Answer

SiggyF picture SiggyF · Aug 16, 2010

You can use the collections.Counter

counter = collections.Counter()
for d in dict1: 
    counter.update(d)

Or, if you prefer oneliners:

functools.reduce(operator.add, map(collections.Counter, dict1))