Ken
Ken

Reputation: 125

Finding index number of dictionary item in a list based on a given value

I'm trying to access the index number of a dictionary that is stored within a list. I'm trying to print out a statement based on this index but I'm unsure of how to go about it.

Here's my current code:

def getSpecies(self, animalName):
        for items in self.animalList:
            for key, value in items.items():
                if self.animalName == value:
                    type = self.animalList[itemsIndex]['Type']
                    print (str(self.animalName) + "' is a " + type)

Where self.animalName is a user input and self.animalList contains the list of dictionaries.

I want the example output to be:

Shamu is a Whale

An example of how the list looks like is this:

self.animalList = [{'Litter': '3', 'Type': 'Whale', 'Mass': '300', 'Name': 'Shamu'}, 
                   {'Litter': '0', 'Type': 'Bird', 'Mass': '5', 'Name': 'Woody'}]

Upvotes: 1

Views: 37

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49784

You want enumerate like:

for itemsIndex, items in enumerate(self.animalList):

Upvotes: 1

Related Questions