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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4207790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:46:01  来源:igfitidea点击:

What exception is thrown when key is not found in Python dictionary?

pythonexceptiondictionary

提问by sivabudh

If I have:

如果我有:

map = { 'stack':'overflow' }

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

Couldn't find it on the web. =(

在网上找不到它。=(

采纳答案by fabrizioM

KeyError

if you do it on the console without the try block will tell it to you

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

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

回答by John Ledbetter

Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> map = { 'a' : 'b' }
>>> print map['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> 

So a wild guess might be...a KeyError?

所以一个疯狂的猜测可能是...a KeyError?

回答by anijhaw

Its called KeyError

它叫做KeyError

>>d={1:2}

>>d[2]

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

回答by user225312

KeyError.

KeyError.

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

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

回答by Kushan Gunasekera

If you don't know the specific exception to handle, you can simply do this kind of thing,

如果你不知道具体要处理的异常,你可以简单地做这种事情,

map = {'stack': 'overflow'}

try:
    map['experts-exchange']
except Exception as inst:
    print(type(inst))       # the exception instance
    print(inst.args)        # arguments stored in .args
    print(inst)             # __str__ allows args to be printed directly,
                            # but may be overridden in exception subclasses

The out put of the above code is,

上面代码的输出是,

<class 'KeyError'>
('experts-exchange',)
'experts-exchange'

When an exception occurs, it may have an associated value, also known as the exception's argument. The presence and type of the argument depend on the exception type.

当异常发生时,它可能有一个关联的值,也称为异常的参数。参数的存在和类型取决于异常类型。

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str __()so the arguments can be printed directly without having to reference .args. One may also instantiate an exception first before raising it and add any attributes to it as desired.

except 子句可以在异常名称之后指定一个变量。该变量绑定到一个异常实例,参数存储在 instance.args 中。为方便起见,异常实例定义了__str __()以便可以直接打印参数而无需引用 .args。也可以在引发异常之前先实例化异常,并根据需要向其添加任何属性。