samedi 8 octobre 2016

How can I compare 2 dictionaries?

I have two dictionaries

dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4}
dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']}

I want to compare the two dictionaries and create a new one with the keys from dict_b and values from dict_aif the values from dict_b match. I would expect to see:

new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]}

I have tried the following code:

for name, guess in dict_b.items():
    if guess == i in dict_a.values():
        new_dict[name].append(i)  
print(new_dict)

I get the error NameError: name 'i' is not definedbut I'm not sure how to define 'i'.

Thanks for any help

Aucun commentaire:

Enregistrer un commentaire