当在Python字典中找不到键时,会引发什么异常?

2024-05-19 09:48:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有:

map = { 'stack':'overflow' }

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

在网上找不到。=(一)


Tags: themapthathereexchangeisstacktype
3条回答

它被称为键错误

>>d={1:2}

>>d[2]

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

KeyError

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

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

如果你在控制台上不使用try块,就会告诉你

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

相关问题 更多 >

    热门问题