Possible Duplicate:
How to sum dict elements
I have a list of dictionaries as following:
[{'Name': 'A', 'amt':100},
{'Name': 'B', 'amt':200},
{'Name': 'A', 'amt':300},
{'Name': 'C', 'amt':400},
{'Name': 'C', 'amt':500},
{'Name': 'A', 'amt':600}]
I want to sum amt
for each name
and get following result in list of dict:
[{'Name':'A', 'amt':1000},
{'Name':'B', 'amt':200},
{'Name':'C', 'amt':900}]
from collections import defaultdict
c = defaultdict(int)
for d in list_of_dictionaries:
c[d['Name']] += d['amt']
It produces c
:
{'A': 1000, 'C': 900, 'B': 200}
To convert it to list of dictionaries:
[{'Name': name, 'amt': amt} for name, amt in c.items()]
Result:
[{'Name': 'A', 'amt': 1000}, {'Name': 'C', 'amt': 900}, {'Name': 'B', 'amt':200}]
Another possible solution, this time using itertools:
lst = [
{'Name': 'A', 'amt':100},
{'Name': 'B', 'amt':200},
{'Name': 'A', 'amt':300},
{'Name': 'C', 'amt':400},
{'Name': 'C', 'amt':500},
{'Name': 'A', 'amt':600}]
import itertools as it
keyfunc = lambda x: x['Name']
groups = it.groupby(sorted(lst, key=keyfunc), keyfunc)
[{'Name':k, 'amt':sum(x['amt'] for x in g)} for k, g in groups]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With