Binnie Binnie - 1 year ago 59
Python Question

Accessing items in lists within dictionary python

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:


This seems like a simple thing but I just can't figure it out. Any help is awesome.

phg phg
Answer Source

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.