Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
Nazmul Hasan Avatar asked Aug 16 '10 05:08

Nazmul Hasan


People also ask

How do you sum values in a dictionary?

USE sum() TO SUM THE VALUES IN A DICTIONARY. Call dict. values() to return the values of a dictionary dict. Use sum(values) to return the sum of the values from the previous step.

How do you count the elements of a dictionary?

By using the len() function we can easily count the number of key-value pairs in the dictionary.

Is dict () and {} the same?

The setup is simple: the two different dictionaries - with dict() and {} - are set up with the same number of elements (x-axis). For the test, each possible combination for an update is run.


2 Answers

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)) 
like image 181
SiggyF Avatar answered Oct 01 '22 08:10

SiggyF


A little ugly, but a one-liner:

dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1) 
like image 40
carl Avatar answered Oct 01 '22 09:10

carl