根据给定值查找列表中字典项的索引号

时间:2018-03-22 00:52:36

标签: python python-2.7 list class dictionary

我试图访问存储在列表中的字典的索引号。我试图根据这个索引打印出一份声明,但我不确定如何去做。

这是我目前的代码:

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)

其中self.animalName是用户输入,self.animalList包含词典列表。

我希望示例输出为:

Shamu is a Whale

列表的示例如下:

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

1 个答案:

答案 0 :(得分:1)

您希望enumerate喜欢:

for itemsIndex, items in enumerate(self.animalList):
相关问题