-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,360
  • 2
  • 11
  • 28

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,777
  • 2
  • 20
  • 23