Reputation: 21
thanks for help in advance!
I try to simplify my problem: I have a nested dict looking like: after that I wrote a for loop to calculate a ratio of the nested dict values
d={'a' :{ '1990': 10, '1991':20, '1992':30},'b':{ '1990':15, '1991':40, '1992':50}}
for key in d:
rate = d[key]['1990']/d[key]['1992']
print(rate)
now I would like to create a new key value pair for each nested dict, so that in the end it looks like:
d = {'a' :{ '1990': 10, '1991':20, '1992':30, 'rate':0.33333},'b':{ '1990':15, '1991':40, '1992':50, 'rate':0.3}}
or creating a new dict looking like:
d2 = {'a':{'rate':0.3333}, 'b':{'rate':0.3}}
please help with the solution easiest for you, I think adding to the existing dict would be better?
thank you!
Upvotes: 0
Views: 4583
Reputation: 294
You can simply insert the key "rate" which has the value you've calculated:
d = {
'a' :{ '1990': 10, '1991':20, '1992':30},
'b':{ '1990':15, '1991':40, '1992':50}
}
for key in d:
rate = d[key]['1990']/d[key]['1992']
print(rate)
d[key]['rate']=rate
print d
FYI, in case you use python2, you should do
rate = float(d[key]['1990'])/d[key]['1992']
.
Upvotes: 2