Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading