【问题标题】:How do you handle different KeyError in your code您如何处理代码中的不同 KeyError
【发布时间】:2020-07-25 17:37:01
【问题描述】:

假设我的字典可以有 3 个不同的键值对。如果条件不同,我如何处理不同的 KeyError。

我们说吧。

Dict1 = {'Key1':'Value1,'Key2':'Value2','Key3':'Value3'}

现在如果我尝试 Dict1['Key4'],它将通过我 KeyError: 'Key4',

我想处理它

except KeyError as error:
     if str(error) == 'Key4':
        print (Dict1['Key3']
     elif str(error) == 'Key5':
        print (Dict1['Key2']
     else:
        print (error)

在 if 条件下没有被捕获,它仍然在 else 块中。

【问题讨论】:

  • 使用in 而不是==
  • 试过了,还是不行
  • 反过来说

标签: python exception keyerror


【解决方案1】:

Python KeyErrors 比仅使用的键长得多。您必须检查 "Key4" 是否 in 错误,而不是检查它是否 等于 错误:

except KeyError as error:
     if 'Key4' in str(error):
        print (Dict1['Key3'])
     elif 'Key5' in str(error):
        print (Dict1['Key2'])
     else:
        print (error)

【讨论】:

  • 它没有用,为了测试我打印了 str(error) 它与假设“Key4”完全相同,但仍然没有进入 if 块
  • 哦,好吧,所以你在比较另一种方式,明白了。谢谢
【解决方案2】:

您也可以使用简单的方法:

dict1 = {'Key1' : 'Value1', 'Key2': 'Value2', 'Key3': 'Value3' }

key4 = dict1['Key4'] if 'Key4' in dict1 else dict1['Key3']
key5 = dict1['Key5'] if 'Key5' in dict1 else dict1['Key2']

【讨论】:

    【解决方案3】:

    如果键不存在,您也可以使用dict.get() 为您提供默认值:

    dict1 = {'Key1' : 'Value1', 'Key2': 'Value2', 'Key3': 'Value3' }
    
    print(dict1.get('Key4', dict1.get('Key3')))
    # Value3
    
    print(dict1.get('Key4', dict1.get('Key2')))
    # Value2
    

    来自docs

    如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为无,因此此方法永远不会引发KeyError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多