【问题标题】:What exception is thrown when key is not found in Python dictionary?在 Python 字典中找不到键时会引发什么异常?
【发布时间】:2011-05-11 14:28:57
【问题描述】:

如果我有:

map = { 'stack':'overflow' }

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

在网上找不到。 =(

【问题讨论】:

  • 你在哪里看的? docs.python.org/library/stdtypes.html 的页面说“d[key] -- 返回 d 的项目,其中包含 key key。如果 key 不在地图中,则引发 KeyError。”
  • 我基本上在 Bing 中输入了“Python 字典异常”并在前 3 个链接后放弃了。以为我可以在 SO 上得到更快的答案。 =p 但感谢您在此处提供参考链接。
  • 您应该使用交互式控制台来查看这样的结果。
  • 我认为这个问题还不错,因为当有人搜索它时,它会显示在搜索引擎上,而不必搜索它,对吧?
  • 这有点讽刺,因为如果你搜索 Python 抛出的内容,如果你寻找一个不存在的键,这是谷歌的最高结果......谢谢你 ShaChris23

标签: python exception dictionary


【解决方案1】:
KeyError

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

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

【讨论】:

  • 谢谢。我在发布之前在控制台上尝试过,但我不知道“KeyError”是实际的异常类型!菜鸟。大声笑。
  • 选择您的答案,因为您的控制台建议让我意识到 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'

【讨论】:

    【解决方案3】:

    它叫KeyError

    >>d={1:2}
    
    >>d[2]
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    KeyError: 2
    

    【讨论】:

      【解决方案4】:
      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'
      >>> 
      

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

      【讨论】:

        【解决方案5】:

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

        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
        

        以上代码的输出是,

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-15
          • 2014-04-09
          • 2020-02-15
          • 1970-01-01
          相关资源
          最近更新 更多