Home > Net >  Sum up the values inside nested python dictionaries if they have the same key
Sum up the values inside nested python dictionaries if they have the same key

Time:04-30

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?

CodePudding user response:

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)

CodePudding user response:

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]
  • Related