Skip to content Skip to sidebar Skip to footer

Python : Get The Sum Of Values Of A Key In List Of Dictionaries

I have a list of dictionaries. Example: l = [{'a' : 1}, {'b' : 5}, {'a' : 10}, {'b' : 10}, {'a' : 10} ] I want to get the sum of the each key like this {

Solution 1:

Use Counter

>>> from collections import Counter
>>> c=Counter()
>>> for d in l:
...     c.update(d)
...
>>> dict(c)
{'a': 30, 'b': 15}

Post a Comment for "Python : Get The Sum Of Values Of A Key In List Of Dictionaries"