python-3.x - 尝试通过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"
]
}
]
解决方案
问题不在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 块的步骤。
推荐阅读
- python - 当python中的字符串不在时,什么是大O表示法
- javascript - 无法将数据绑定到jsp中的模型属性列表
- c# - convert string to decimal to string in c#
- regex - 如果在仅包含字母(无数字)的复合词中,则匹配破折号
- python - Plotting time series by year only in Matplotlib
- c# - 当我使用 Aspose WorkbookDesigner 打开 excel 模板文件时,出现“错误 xml 命名空间”异常
- docker - Setup docker toolbox behind proxy on Windows
- c - Read and write data through USB port
- java - i get this error : Can't convert object of type java String to type com.example
- sql - JSON 对象为 null 但不知何故它的子对象不是?