Skip to content

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 KeyError

  • Use dict.获取(键, 默认) 到 provide fallback 值

  • 检查 如果键 in dict 之前 accessing 使用 dict[键]

如何预防

  • Use .获取() 相反的 [] 当键 可能不 exist

  • Use defaultdict 从 集合 for dictionaries 使用默认值

相关资源

相关术语

相关课程

  • 数据类型

    学习关于 Python dictionaries and 数据类型

相关练习

← 返回语言