Drew Ackerman Drew Ackerman - 5 months ago 8
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):
pass


I create an object -

Dumbo = Elephant()


And try to print out its food choice

>>print(Dumbo.animal_food())
>>Grass


I expect it to print out

>>Grass
>>Trees


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

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__]