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:

{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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

Method 2

You can avoid utilizing a defaultdict (and therefore importing a library) if you use the dictionary method .get() which already provides functionality to avoid missing keys:

previous_sums = dict()

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x