在Python字典中找不到键时抛出什么异常?

45 投票
5 回答
56121 浏览
提问于 2025-04-16 07:13

如果我有:

map = { 'stack':'overflow' }

try:
  map['experts-exchange']
except:                       <--- What is the Exception type that's thrown here?
  print( 'is not free' )

在网上找不到这个。 =(

5 个回答

5

这叫做键错误

>>d={1:2}

>>d[2]

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 2
11

KeyError 是一种错误类型。

当你在程序中尝试访问一个字典(可以理解为一种存储数据的方式)里不存在的键(就像是字典里的一个标签)时,就会出现这个错误。简单来说,就是你想要找的东西不在你给它的列表里。

>>> x = {'try': 1, 'it': 2}
>>> x['wow']

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    x['wow']
KeyError: 'wow'
59
KeyError
>>> a = {}
>>> a['invalid']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'invalid'
>>> 

如果你在控制台上执行这个代码,而没有使用try块,它会直接告诉你错误。

撰写回答