What is the Python keyerror?

A map is a data structure in Python that maps a collection of values onto another collection of values.

A dictionary is the most commonly used mapping in Python. The ​dictionary allows working with key, value pairs. Each value has a key associated with it and this key can be used to lookup the value.

The keyerror occurs when the key used for a lookup does not exist in the mapping.

Consider a phone book that is represented as a dictionary in Python. The names can be thought of as the keys and the phone numbers as the values. Suppose that the phone book does not contain an entry for Ellen. Now, python will throw a keyerror if someone attempts to look for Ellen’s number in the dictionary.

svg viewer

Examples

The following examples will show a code snippet that results in a keyerror and then illustrates ways to avoid getting this error.

Getting the keyerror:

# Creating a dictionary to store names and phone numbers
phonebook = {"Alice" : "12345", "Bob" : "45678", "Dan" : "34567"}
#Trying to lookup Ellen's number
print (phonebook["Ellen"])

Solution one

The .get() method can be used to avoid getting the keyerror. This function takes in two arguments.

  • The first argument is the key for ​which the value is required.

  • The second argument is optional. If given, it serves as the default value in case a value is not found.

If the key is found then the corresponding value is returned. If the​ key cannot be found and the default value is specified then the default value is returned. Else, a None object is returned.

# Creating a dictionary to store names and phone numbers.
phonebook = {"Alice" : "12345", "Bob" : "45678", "Dan" : "34567"}
#Using the get method with default value
print (phonebook.get("Ellen",0))
#Using the get method without the default value
print (phonebook.get("Ellen"))

Solution Two

The try-except block is a popular method for exception handling.

# Creating a dictionary to store names and phone numbers
phonebook = {"Alice" : "12345", "Bob" : "45678", "Dan" : "34567"}
try:
print (phonebook["Ellen"])
except:
print ("The phone book does not contain a record for this key.")
Copyright ©2024 Educative, Inc. All rights reserved