yaniv14
yaniv14

Reputation: 711

How to combine values in python list of dictionaries

I have a list of dictionaries that look like this:

l = [{'name': 'john', 'amount': 50}, {'name': 'al', 'amount': 20}, {'name': 'john', 'amount': 80}]

is there any way to combine/merge the matching name values dictionaries and sum the amount also?

Upvotes: 1

Views: 94

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can use a collections.Counter() object to map names to amounts, summing them as you go along:

from collections import Counter

summed = Counter()
for d in l:
    summed[d['name']] += d['amount']
result = [{'name': name, 'amount': amount} for name, amount in summed.most_common()]

The result is then also sorted by amount (highest first):

>>> from collections import Counter
>>> l = [{'name': 'john', 'amount': 50}, {'name': 'al', 'amount': 20}, {'name': 'john', 'amount': 80}]
>>> summed = Counter()
>>> for d in l:
...     summed[d['name']] += d['amount']
... 
>>> summed
Counter({'john': 130, 'al': 20})
>>> [{'name': name, 'amount': amount} for name, amount in summed.most_common()]
[{'amount': 130, 'name': 'john'}, {'amount': 20, 'name': 'al'}]

Upvotes: 7

Related Questions