Handling Dictionary KeyError Exceptions
A KeyError
occurs when you attempt to access a key that does not exist in a dictionary.
The following example raises a KeyError
by attempting to access the non-existent age
key in a dictionary.
Example of KeyError Occurrence
user_info = { "username": "user123", "email": "user123@example.com", "location": "New York" } # "age" key does not exist, KeyError raised user_age = user_info["age"]
To prevent KeyError
, you should verify the existence of a key in the dictionary before attempting to access it.
You can do this using the in
operator or the get()
method.
In the next lesson, we will delve deeper into the in
operator and get()
method.
Quiz
0 / 1
The in
keyword can be used to check whether a key exists in a dictionary before accessing it.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result