Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sum on keys for List of Dictionaries [duplicate]

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}]
like image 464
Mav Avatar asked Dec 21 '11 02:12

Mav


2 Answers

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}]
like image 114
jfs Avatar answered Oct 11 '22 21:10

jfs


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]
like image 33
Óscar López Avatar answered Oct 11 '22 22:10

Óscar López