I have data in two separate objects of the same shape, and I want to add the values together. The issue is that each object is a dictionary of dictionaries of lists of dictionaries. I have provided an example of what it looks like below.
data1 = {
'months': {
'type1': [
{'name': 'Month 1', 'value': 10, 'sequence': 1},
{'name': 'Month 2', 'value': 20, 'sequence': 2},
{'name': 'Month 3', 'value': 30, 'sequence': 3}
],
'type2': [
{'name': 'Month 1', 'value': 10, 'sequence': 1},
{'name': 'Month 2', 'value': 20, 'sequence': 2},
{'name': 'Month 3', 'value': 30, 'sequence': 3}
]
},
'years': {
'type1': [
{'name': 'Year 1', 'value': 10, 'sequence': 1},
{'name': 'Year 2', 'value': 20, 'sequence': 2},
{'name': 'Year 3', 'value': 30, 'sequence': 3}
],
'type2': [
{'name': 'Year 1', 'value': 10, 'sequence': 1},
{'name': 'Year 2', 'value': 20, 'sequence': 2},
{'name': 'Year 3', 'value': 30, 'sequence': 3}
]
}
}
The above is a simplified version of what the actual data looks like. For sake of this example, let us say that data2
would be identical to data1
with regards to values. Note: they are identical with regards to shape.
I would like to be able to iterate over these nested dictionary/lists and add the value
s together for each month within each type, and maintain all other necessary information.
I.e. data1
+ data2
= data_output
(provided below).
data_output = {
'months': {
'type1': [
{'name': 'Month 1', 'value': 20, 'sequence': 1},
{'name': 'Month 2', 'value': 40, 'sequence': 2},
{'name': 'Month 3', 'value': 60, 'sequence': 3}
],
'type2': [
{'name': 'Month 1', 'value': 20, 'sequence': 1},
{'name': 'Month 2', 'value': 40, 'sequence': 2},
{'name': 'Month 3', 'value': 60, 'sequence': 3}
]
},
'years': {
'type1': [
{'name': 'Year 1', 'value': 20, 'sequence': 1},
{'name': 'Year 2', 'value': 40, 'sequence': 2},
{'name': 'Year 3', 'value': 60, 'sequence': 3}
],
'type2': [
{'name': 'Year 1', 'value': 20, 'sequence': 1},
{'name': 'Year 2', 'value': 40, 'sequence': 2},
{'name': 'Year 3', 'value': 60, 'sequence': 3}
]
}
}
I have tried applying the solutions listed in the following answers, but with no success (which may be due to my misunderstanding since I am new to Python):
- Python iterate over multi value nested dictionary
- Iterate over nested dictionary
- iterate over nested dictionaries
- Iterate over Nested dictionary with similar keys but different values
- Python how to iterate over nested dictionary and change values?
Based on the above links, I understand that variations on this question have been asked before, but I cannot seem to make their solutions work for me, so any help with this would be greatly appreciated. Thank you!