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

siv*_*udh 32 python dictionary exception

如果我有:

map = { 'stack':'overflow' }

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

无法在网上找到它.=(

fab*_*ioM 49

KeyError
Run Code Online (Sandbox Code Playgroud)

如果你在没有try块的情况下在控制台上执行它会告诉你

>>> a = {}
>>> a['invalid']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'invalid'
>>> 
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。我在发布之前在控制台上尝试过,但我不知道“KeyError”是实际的异常类型!新手。哈哈。 (2认同)

use*_*312 9

KeyError.

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

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    x['wow']
KeyError: 'wow'
Run Code Online (Sandbox Code Playgroud)


ani*_*haw 5

它叫做KeyError

>>d={1:2}

>>d[2]

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 2
Run Code Online (Sandbox Code Playgroud)