Skip to main content
Practice

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.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.