假設我的字典可以有 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
提交
取消