xxxxxxxxxx
my_dict = {'key1': 'value1', 'key2': 'value2'}
key_to_find = 'key3' # Key that does not exist in the dictionary
# Using the get() method with a default value
value = my_dict.get(key_to_find, 'Key not found')
print(value)
xxxxxxxxxx
"""
KeyError exceptions occur when you attempt to index a dictionary with a key
that doesn't exist. Simple example below
"""
my_dict = {
'key1': 1,
'key2': 2,
'key3': 3,
}
# Outputs
print (my_dict['key1']) # 1
print (my_dict['key2']) # 2
print (my_dict['key3']) # 3
print (my_dict['key4']) # KeyError: 'key4'