首页 > 解决方案 > 尝试通过python中的字符串引用访问列表项时出现KeyError

问题描述

animals = [
    {
            "bird": ["crow"]
    },
    {
            "fish": ["salmon", "anchovy", "monkfish"]
    }
]
def getBirdsArray():
    birds = []
    fishes = []
    for animal in animals:
        for r in animal["bird"]:
            birds.append(r)
            print("birds are", birds)

        for r in animal["fish"]:
            fishes.append(r)
            print("fishes are", fishes)

预期:鸟是 ["crow"] 鱼是 ["salmon", "anchovy", "monkfish"]

实际结果:

  for r in animal["fish"]:
KeyError: 'fish'

使用get("fish")没有帮助。

我不想做动物[0 或动物[1],但我希望通过字符串索引而不是使用数字索引来灵活地查找项目。我使用数组作为包装器,因为数组包含多个键,这是一种模式。

将来这种结构将成为这只是表明它将越来越嵌套,所以我必须小心我现在使用的方法。

animals = [
{
   "birds":[
      "id":23,
      "color":"blue",
      "owner":[
         {
            "id":23
         },
         {
            "ownerName":"Harold"
         }
      ]
   ]
},
{
   "fish":[
      "salmon",
      "anchovy",
      "monkfish"
   ]
}
  ]

标签: python-3.x

解决方案


问题不在for循环中。问题在于表达式animal["bird"]animal["fish"]

考虑第一次执行循环。在这种情况下,

animal = {"bird": ["crow"]}

你会注意到关键的“鱼”完全不存在。那么当你animal["fish"]for循环内执行时会发生什么?你得到一个KeyError!第二次迭代也会发生同样的事情,关键“鸟”完全不存在。


dict.get()可以抵抗此问题*,如果您为其提供默认值以在未找到密钥的情况下返回(在这种情况下,空列表应导致for跳过循环内部而不会导致错误)。此修改应修复您的代码以按预期工作:

for animal in animals:
        for r in animal.get("bird", []):
            birds.append(r)
            print("birds are", birds)

        for r in animal.get("fish", []):
            fishes.append(r)
            print("fishes are", fishes)

*dict.get()本质上等同于以下两个函数之一:

def get(self, key, default=None):
    try:
        return self[key]
    except KeyError:
        return default

def get(self, key, default=None):
    if key in self:
        return self[key]
    else:
        return default

它比这复杂一点,因为它总是如此,但它节省了必须放置整个 try/except 块的步骤。


推荐阅读