简体   繁体   中英

Python 3: creating a dictionary/ adding values to a nested dictionary

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!

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'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM