I have a dictionary that has keys associated with lists.
mydict = {'fruits': ['banana', 'apple', 'orange'],
'vegetables': ['pepper', 'carrot'],
'cheese': ['swiss', 'cheddar', 'brie']}
What I want to do is use an if statement that if I search for item and its in any of the lists within the dictionary it will return the key. This is what I was trying:
item = cheddar
if item in mydict.values():
print key
but it doesn't do anything, the output should be:
cheese
This seems like a simple thing but I just can't figure it out. Any help is awesome.
keys() is a method which allows to access keys of a dictionary. .get(key) is method by how we can access every key one by one. Then by using nested loop we can access every key and its values one by one remained in a list.
Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of the character string. It is a collection whose values are accessible by key. The dictionary is a mapping of keys and values. A list is a sequence of indexed and ordered values.
You'll have to use a for
, a simple if
is not enough to check an unknown set of lists:
for key in mydict.keys():
if item in mydict[key]:
print key
An approach without an explicit for
statement would be possible like this:
foundItems = (key for key, vals in mydict.items() if item in vals)
which returns all keys which are associated with item
. But internally, there's still some kind of iteration going on.
mydict = {'fruits': ['banana', 'apple', 'orange'],
'vegetables': ['pepper', 'carrot'],
'cheese': ['swiss', 'cheddar', 'brie']}
item = "cheddar"
if item in mydict['cheese']:
print ("true")
this works, but you have to reference the keys in the dictionary like cheese, vegetables etc instead because of the way you made the dictionary, hope this helps!
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