Handling Dictionary KeyError Exceptions
KeyError
occurs when you attempt to access a key that does not exist in a dictionary.
The code below demonstrates a KeyError
by attempting to access a 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 achieve this by using the in
operator or utilizing the get()
method.
In the next lesson, we will delve deeper into the in
operator and get()
method.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.