Python KeyError Exception
Example
A KeyError
occurs if you try access a dictionary with a key that does not exist:
fruit = {"name": "apple", "color": "red"}
print(fruit["price"])
Try it Yourself »
Definition and Usage
The KeyError
exception occurs when you use a key on a dictionary, and the key does not exist.
You can handle the KeyError
in a try...except
statement, see the example below.
Exception Handling
Example
Handling the IndexError
in a try...except
statement:
fruit = {"name": "apple", "color": "red"}
try:
print(fruit["price"])
except KeyError:
print("You are trying to access a dictionary item that does not exist!")
except:
print("Something else went wrong")
Try it Yourself »