简体   繁体   中英

How to get values in nested dictionary according to keys given by lists?

I am trying to get values in a nested dictionary according to keys given by lists.

Here is my code:

  ops = {
    'OP1' : {'W1':5, 'w3':6, 'w4':7, 'w5':9},
    'OP3' : {'W21':61, 'w22':56, 'w23':76, 'w24':96},
    'OP4' : {'W31':61, 'w32':56, 'w33':76, 'w34':96},
    'OP5' : {'W41':61, 'w42':56, 'w43':76, 'w44':96},

}

lsta = ['OP1', 'OP3', 'OP4', 'OP5']
lstd = ['w3', 'w22', 'w32', 'w44']

#I tried

for i in lsta:
    lste=[]
    for ele in lstd:
        if ele == ops_machine[i]:
            e = ops_machine[i][ele]


KeyError: 'OP1'    

What I want are the correponding values of each key given by lstd, which means: result = [6, 56, 56, 96]

Could someone help me please ? Thanks

The problem is that you're using a nested loop, when you should be iterating over both lists at the same time. You can use zip for that:

[ops[d1][d2] for d1, d2 in zip(lsta, lstd)]
# [6, 56, 56, 96]

This does the job:

lsta = ['OP1', 'OP3', 'OP4', 'OP5']
lstd = ['w3', 'w31', 'w4', 'w51']


ops = {
       'OP1' : {'W1':5, 'w3':6, 'w4':7, 'w5':9},
       'OP3' : {'W11':61, 'w31':56, 'w41':76, 'w51':96},
       'OP4' : {'W11':61, 'w4':56, 'w41':76, 'w51':96},
       'OP5' : {'W11':61, 'w666':56, 'w41':76, 'w51':96},
    }
for i in lsta:
    if i in ops.keys():
        sub_dict = ops[i]
        for j in lstd:
            if j in sub_dict.keys():
                print (sub_dict[j])

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