MingyJ MingyJ - 4 years ago 93
Python Question

Comparing List against Dict - return key if value matches list

This is Python 3.6

I need help comparing a list against a dictionary and if there is match I need to return the dictionaries key.

champ_ids = [0, 36, 85]

champ_dict = {Bob : 0, Carly: 36, Freddy : 85, Megan : 14, Dilbert : 69}

for item in champ_dict.items() and champ_ids:

That prints all the matching numbers so in this case
0, 36, 85
which is perfect. How do I make it return
Bob, Carly, Freddy
(the keys) if those values are found in both places, instead of returning the values that match

Answer Source

Notice that this code in the question is not doing what you imagine:

for item in champ_dict.items() and champ_ids:

The above does not check if the item is in both the dictionary and the list (that's not how in, and work in Python!). It's simply iterating over the champ_ids list, and nothing more. Try this instead:

champ_ids  = [0, 36, 85]
champ_dict = {'Bob' : 0, 'Carly': 36, 'Freddy' : 85, 'Megan' : 14, 'Dilbert' : 69}
[k for k, v in champ_dict.items() if v in champ_ids]

The above will compare each value in the dictionary and if it's present in the list it'll add the corresponding key to an output list. For instance, this is the output for the test data in the question:

['Freddy', 'Bob', 'Carly']

Now you can use it as needed, print() it if you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download