猿问

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

假设我的字典可以有 3 个不同的键值对。我如何使用 if 条件处理不同的 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 块。


慕妹3146593
浏览 152回答 3
3回答

Helenr

Python KeyErrors 比所使用的键长得多。您必须检查是否"Key4"在错误中,而不是检查它是否等于错误:except KeyError as error:     if 'Key4' in str(error):        print (Dict1['Key3'])     elif 'Key5' in str(error):        print (Dict1['Key2'])     else:        print (error)

杨魅力

您还可以使用简单的方法: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']

慕村9548890

dict.get()如果键不存在,您也可以使用为您提供默认值:dict1 = {'Key1' : 'Value1', 'Key2': 'Value2', 'Key3': 'Value3' }print(dict1.get('Key4', dict1.get('Key3')))# Value3print(dict1.get('Key4', dict1.get('Key2')))# Value2从文档:如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为 None,因此此方法永远不会引发KeyError
随时随地看视频慕课网APP

相关分类

Python
我要回答