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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With