Drew Ackerman Drew Ackerman - 1 year ago 71
Python Question

Iterating over a list value in a dictionary

I have a parent class as such -

class Animal(object):

animalFoods = {'Elephant': ['Grass', 'Trees'], 'Turtle': 'Fish'}

def animal_food(self):
foods = Animal.animalFoods[self.__class__.__name__]
for food in foods:
return food

Then I have a subclass -

class Elephant(Animal):

I create an object -

Dumbo = Elephant()

And try to print out its food choice


I expect it to print out


I see how it is working by finding the key in the animalFoods dictionary, but i am not sure why it is not returning both values in the value list.

Pointers towards additional reading are appreciated over just providing a quick and dirty answer, as this is my first time working with dictionaries beyond single values.

Answer Source

return food will immediately end execution of your animal_food; it will not attempt to complete the loop. If you wanted to get very fancy, you could use yield food to turn the method into a generator, but probably for this example you just want to replace the method body completely:

def animal_food(self):
    return Animal.animalFoods[self.__class__.__name__]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download