0

I am trying to print out the key associated with a value item in a dictionary if that value item is put forward when I call a function.

For example (and this works):

def test(pet):
  dic = {'Dog': 'der Hund' , 'Cat' : 'der Katze' , 'Bird': 'der Vogel'}

  items = dic.items()
  key = dic.keys()
  values = dic.values()
  for x, y in items:
    if y == pet:
      print x

However, whenever I add multiple values to a key it stops working and I don't know why?

dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : 'der Katze' , 'Bird': 'der Vogel'}

give me no output it doesn't print x.

Can someone help?

askewchan
  • 45,161
  • 17
  • 118
  • 134
Danrex
  • 1,657
  • 4
  • 31
  • 44

2 Answers2

3

Your condition above:

...
for x, y in items:
    if y == pet:
...

tests if the value (of key, value pair) IS the value pet. However, when the dictionary value is a list, you really want to know if pet is in the list. So you could try:

...
for x, y in dic.items():
    if pet in y:
        print x

Note, that both of these cases return True:

pet = "crocodile"
list_value = ["I", "am", "a", "crocodile"]
single_value = "crocodile"

pet in list_value
--> True

pet in single_value
--> True

Hope this helps

Nick Burns
  • 973
  • 6
  • 4
  • That most certainly did and thank you for the fast reply and easy to understand explanation!!!!! – Danrex May 17 '13 at 01:54
0

It doesn't work because you are mixing strings and lists, why not make them all lists?

def test(pet): 
  items = dic.items()
  key = dic.keys()
  values = dic.values()
  for x, y in items:
      for item in y: # for each item in the list of dogs
          if item == pet:
              print x

dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : ['der Katze'] , 'Bird': ['der Vogel']}
test('der Hund')

>>> 
Dog

Since Order doesn't seem to matter in your case, and you are only checking membership, it would be better to use a set instead. Also you can simply check if pet in y instead of iteration through yourself.

def test(pet):
  for k, v in dic.items():
      if pet in v:
          print k

dic = {'Dog': {'der Hund', 'der Katze'}, # sets instead of lists
       'Cat': {'der Katze'},
       'Bird': {'der Vogel'}}

test('der Hund')

>>> 
Dog
jamylak
  • 128,818
  • 30
  • 231
  • 230