简体   繁体   English

您如何处理代码中的不同 KeyError

[英]How do you handle different KeyError in your code

Let say my dictionary can have 3 different key-value pairs.假设我的字典可以有 3 个不同的键值对。 How do i handle different KeyError with if condition.我如何使用 if 条件处理不同的 KeyError。

Let's say.比方说。

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

Now if I try Dict1['Key4'], it will through me KeyError: 'Key4',现在如果我尝试 Dict1['Key4'],它将通过我 KeyError: 'Key4',

I want to handle it我想处理它

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

It's not getting captured in if condition, it still goes in else block.它没有在 if 条件下被捕获,它仍然进入 else 块。

Python KeyErrors are much longer than just the key used. Python KeyErrors 比仅使用的密钥长得多。 You have to check if "Key4" is in the error, as opposed to checking if it is equal to the error:您必须检查"Key4"是否错误中,而不是检查它是否等于错误:

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

You can also use a simple approach:您还可以使用简单的方法:

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']

You could also just use dict.get() to give you a default value if the key doesn't exist:如果键不存在,您也可以使用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

From the docs :文档

Return the value for key if key is in the dictionary, else default.如果键在字典中,则返回键的值,否则返回默认值。 If default is not given, it defaults to None, so that this method never raises a KeyError如果未给出默认值,则默认为 None,因此此方法永远不会引发KeyError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM