Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a word is in a list that is a value of a dictionary

I'm trying to check if a word is in a list that is a value of a dictionary. For example i want to check if 'noodles' is in: {1:['hello', 'hallo', 'salut', 'ciao', 'hola'], 2:['eggs', 'noodles', 'bacon']}

I tried with:

element = 'noodles'
element in myDict.values()

But i get: False

like image 410
Algorne Avatar asked Jan 03 '23 03:01

Algorne


1 Answers

Your code checks if element ('noodles') is a value in the dictionary, and it isn't (the values are lists).

You need to check if element is inside every list.

If you don't care for the key:

print(any(element in value for value in myDict.values()))

If you want to know the key (this will print a list of matching keys):

print([key for key, value in myDict.items() if element in value])

But, generally speaking, if you find yourself having to loop over a dictionary over and over again, you either made a bad choice for what are the keys, or using the wrong data structure altogether.

like image 117
DeepSpace Avatar answered Jan 05 '23 15:01

DeepSpace