Skip to content
Advertisement

How to sum dict elements

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.

Advertisement

Answer

A little ugly, but a one-liner:

dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement