【问题标题】:Finding index number of dictionary item in a list based on a given value根据给定值查找列表中字典项的索引号
【发布时间】:2018-08-31 07:28:07
【问题描述】:

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

这是我当前的代码:

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'}]

【问题讨论】:

  • 索引号是从哪里来的?
  • 我认为最好的说法是,我会提示用户输入存储在列表中的动物的名称,然后我会尝试获取动物的名称并将其与字典中的值进行比较。如果名称匹配,获取索引号..但我不知道如何写。
  • 我想你的第二个 for 循环也没有必要。您只需要找到'Name' 键的值。我也避免使用 type 作为变量名,因为它是内置的。

标签: python python-2.7 list class dictionary


【解决方案1】:

你想要enumerate 喜欢:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2014-09-17
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多