JohnDole
JohnDole

Reputation: 565

Sum of values in a list of dictionaries

My list of dictionaries

[{'key': '', 'value': 494}, {'key': 'cloud', 'value': 63}, {'key': 'cloud', 'value': 44}]

As you can see, my list contains two dictionaries with "key": "cloud". I want to find those duplicates and make a sum out of them.

My desired output:

    [{'key': '', 'value': 494}, {'key': 'cloud', 'value': 107}]

How can I sum up values in a list of dictionaries with the same key?

Upvotes: 1

Views: 62

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

One solution:

from collections import defaultdict

lst = [{'key': '', 'value': 494}, {'key': 'cloud', 'value': 63}, {'key': 'cloud', 'value': 44}]

total = defaultdict(int)
for e in lst:
    total[e["key"]] += e["value"]

res = [{"key" : key, "value" : value} for key, value in total.items()]
print(res)

Output

[{'key': '', 'value': 494}, {'key': 'cloud', 'value': 107}]

Upvotes: 3

Related Questions