Let say my dictionary can have 3 different key-value pairs. How do i handle different KeyError with if condition.
Let's say.
Dict1 = {'Key1' : 'Value1, 'Key2': 'Value2', 'Key3': 'Value3' }
Now if I try Dict1['Key4'], it will through me KeyError: 'Key4',
I want to handle it
except KeyError as error:
if str(error) == 'Key4':
print (Dict1['Key3']
elif str(error) == 'Key5':
print (Dict1['Key2']
else:
print (error)
It's not getting captured in if condition, it still goes in else block.
Python KeyErrors are much longer than just the key used. You have to check if "Key4"
is in the error, as opposed to checking if it is equal to the error:
except KeyError as error:
if 'Key4' in str(error):
print (Dict1['Key3'])
elif 'Key5' in str(error):
print (Dict1['Key2'])
else:
print (error)