假设我的字典可以有 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)

杨魅力
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']
添加回答
举报
0/150
提交
取消