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 up the values inside nested python dictionaries if they have the same key

I want to change values in nested python dictionaries if they have the same key. My original dict contains several nested dicts with a different length. If a nested dict has the same key as a previous nested dict, the value of the previous key should be added to the value of the current key. This is basically stacking the values on top of each other. For better understanding:

Nested dict with ID 2 contains the pair: {525: 6.8}
the next dict, which also contains the key 525, should have the value 6.8 + 6.8 = 13.6 for this key ({525: 13.6}). Another dict with the key 525 should then have the value 13.6 + 6.8 = 20.4 ({525: 20.4}).

This is my dictionary:

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

{2: {510: 8.5, 525: 6.8, 540: 9.5}, 3: {525: 6.8, 540: 9.5}, 4: {525: 6.8, 540: 9.5, 570: 8.7, 585: 10.7, 600: 10.2}, 7: {600: 10.2, 615: 10.1}

This is how it should look like after the transformation:

{2: {510: 8.5, 525: 6.8, 540: 9.5}, 3: {525: 13.6, 540: 19}, 4: {525: 20.4, 540: 28.5, 570: 8.7, 585: 10.7, 600: 10.2}, 7: {600: 20.4, 615: 10.1}}

I’ve already tried to iterate over the nested dicts and to write the values in a list. And then to add the values to the next dict. But in the end I didn’t reached my goal.

Has somebody an idea how to solve this?

>Solution :

You can keep track of the key-value pairs you’ve previously seen using a defaultdict (which returns 0 if a key which it hasn’t seen yet is accessed). For each key in the inner dictionary, add the value of the key when it was last previously seen. Then, update the defaultdict so that the "last previously seen" value is the current value:

from collections import defaultdict
previous_sums = defaultdict(int)

for key, value in data.items():
    for inner_key in value:
        value[inner_key] += previous_sums[inner_key]
        previous_sums[inner_key] = value[inner_key]

print(data)
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