为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3146593 2022-10-06 17:04:59
假设我的字典可以有 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 块。
查看完整描述

3 回答

?
Helenr

TA贡献1780条经验 获得超4个赞

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)


查看完整回答
反对 回复 2022-10-06
?
杨魅力

TA贡献1811条经验 获得超6个赞

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


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


查看完整回答
反对 回复 2022-10-06
?
慕村9548890

TA贡献1884条经验 获得超4个赞

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

文档

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


查看完整回答
反对 回复 2022-10-06
  • 3 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号