Access to items in lists in a python dictionary

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 the if statement, which, if I look for the element and it in any of the lists in the dictionary, it will return the key. This is what I tried:

 item = cheddar if item in mydict.values(): print key 

but he does nothing, the conclusion should be:

 cheese 

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

+7
source share
3 answers

You will need to use for , a simple if not enough to check an unknown set of lists:

 for key in mydict.keys(): if item in mydict[key]: print key 

The approach without an explicit for expression will be possible as follows:

 foundItems = (key for key, vals in mydict.items() if item in vals) 

which returns all the keys associated with item . But inside, there is still some kind of iteration happening.

+7
source
 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 refer to keys in the dictionary, for example cheese, vegetables, etc., instead, because of how you made the dictionary, hope this helps!

+2
source
 mydict = {'fruits': ['banana', 'apple', 'orange'], 'vegetables': ['pepper', 'carrot'], 'cheese': ['swiss', 'cheddar', 'brie']} item = "cheddar" for key, values in mydict.iteritems(): if item in values: print key 

If you are going to do such a search, I think you can create a reverse index for the original mydict to speed up the query:

 reverse_index = {} for k, values in mydict.iteritems(): for v in values: reverse_index[v] = k print reverse_index.get("cheddar") print reverse_index.get("banana") 

Thus, you do not need to move the values list each time to find an element.

+1
source

All Articles