Sum of values in a list of dictionaries

Question:

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?

Asked By: JohnDole

||

Answers:

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}]
Answered By: Dani Mesejo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.