3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
Python KeyErrors 比所使用的鍵長(zhǎng)得多。您必須檢查是否"Key4"在錯(cuò)誤中,而不是檢查它是否等于錯(cuò)誤:
except KeyError as error:
if 'Key4' in str(error):
print (Dict1['Key3'])
elif 'Key5' in str(error):
print (Dict1['Key2'])
else:
print (error)

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
您還可以使用簡(jiǎn)單的方法:
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']

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
添加回答
舉報(bào)