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?
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}]
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?
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}]