'Mapping nested dictionary and upate it in python?
I have nested dictionary and want to sum it most nested dictionary like this:
{
"USA":{
'008612':{
'January':{
'target':345,
'achieved':0
},
'Febuary':{
'target':305,
'achieved':0
},
'March':{
'target':345,
'achieved':0
},
},
'001232':{
'January':{
'target':245,
'achieved':0
},
'Febuary':{
'target':205,
'achieved':0
},
'March':{
'target':105,
'achieved':0
},
}
},
"UK":{
'008612':{
'January':{
'target':645,
'achieved':0
},
'Febuary':{
'target':505,
'achieved':0
},
'March':{
'target':445,
'achieved':0
},
},
'001232':{
'January':{
'target':745,
'achieved':0
},
'Febuary':{
'target':605,
'achieved':0
},
'March':{
'target':405,
'achieved':0
},
}
}
}
Required this type of dictionary that Total dictionary contains the sum of target and achieved of same item code{008612} and same month. For example, the same item code with the same month should be added to the Total dictionary that is newly added:
{
"Total":{
'008612':{
'January':{
'target':990=345+645,
'achieved':0=0+0
},
'Febuary':{
'target':810,
'achieved':0
},
'March':{
'target':790,
'achieved':0
},
},
'001232':{
'January':{
'target':890,
'achieved':0
},
'Febuary':{
'target':810,
'achieved':0
},
'March':{
'target':510,
'achieved':0
},
},
"USA":{
'008612':{
'January':{
'target':345,
'achieved':0
},
'Febuary':{
'target':305,
'achieved':0
},
'March':{
'target':345,
'achieved':0
},
},
'001232':{
'January':{
'target':245,
'achieved':0
},
'Febuary':{
'target':205,
'achieved':0
},
'March':{
'target':105,
'achieved':0
},
}
},
"UK":{
'008612':{
'January':{
'target':645,
'achieved':0
},
'Febuary':{
'target':505,
'achieved':0
},
'March':{
'target':445,
'achieved':0
},
},
'001232':{
'January':{
'target':745,
'achieved':0
},
'Febuary':{
'target':605,
'achieved':0
},
'March':{
'target':405,
'achieved':0
},
}
}
}
Thanks in Advance!
Solution 1:[1]
You will have to loop through the dictionary and its values multiple times, and compute a separate dictionary to store the calculated values. Have written a sample code for your reference:
total = {}
for k, v in data.items(): # data is the original data dict
for ik, iv in v.items():
temp = total.get(ik, {})
if not temp:
total[ik] = iv
else:
for tk, tv in temp.items():
for itk, itv in tv.items():
temp[tk][itk] += iv[tk][itk]
Once the above total dictionary is computed, you can then add it to the original data. Hope this answers your question. Cheers!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Darshit Kothari |
