Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

cheese

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

like image 725
Binnie Avatar asked Jun 15 '12 19:06

Binnie


People also ask

How can I access list values in a dictionary?

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.

How do you handle a dictionary inside a list in Python?

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.


2 Answers

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.

like image 160
phipsgabler Avatar answered Oct 14 '22 07:10

phipsgabler


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!

like image 26
theBigChalk Avatar answered Oct 14 '22 07:10

theBigChalk