-4

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

{
 "a" : 30,
 "b" : 15
}
tsadkan yitbarek
  • 1,264
  • 2
  • 10
  • 23

1 Answers1

3

Use Counter

>>> from collections import Counter
>>> c=Counter()
>>> for d in l:
...     c.update(d)
...
>>> dict(c)
{'a': 30, 'b': 15}
Sunitha
  • 11,422
  • 2
  • 17
  • 22