KeyError: 'x'
错误信息
'x'
快速摘要
你 tried 到获取值 从 dictionary using 键那个 isn't in dictionary.
为什么发生
Typo in 键 name
键是 从不添加到 dictionary
键是 删除 or 数据源 doesn't 包含它
最小示例
✗ 错误代码
d = {"a": 1}
print(d["b"])✓ 修复代码
d = {"a": 1}
print(d.get("b", 0))d["b"] raises KeyError because "b" isn't in the dict — .获取("b", 0) returns the default 0 instead.
如何诊断
Print dictionary 键使用
dict.键()到 see 什么's available检查键 spelling 针对实际键
验证键 exists 使用
如果键 in dict之前 accessing
如何修复
Use
dict.获取(键)哪个返回无相反的 raising KeyErrorUse
dict.获取(键, 默认)到 provide fallback 值检查
如果键 in dict之前 accessing 使用dict[键]
如何预防
Use
.获取()相反的[]当键 可能不 existUse
defaultdict从集合for dictionaries 使用默认值