A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.
How to Handle a Python KeyError
Have you just been greeted by a KeyError? Don’t worry! When a KeyError is raised, it means that you are trying to access a key inside a dictionary that does not exist. Handing and fixing this error is easy when you know how.
KeyErrors can be handled using a try…except block, using the “in” keyword, or by checking for a key in advance using indexing.
In this guide, we’re going to talk about what Python KeyErrors are and why they are raised. We’ll walk through an example of an error and how to fix it so you’ll know how to address KeyErrors in the future.
Let’s get started!
What is a Python KeyError?
A Python KeyError occurs when you attempt to access an item in a dictionary that does not exist using the indexing syntax. This error is raised because Python cannot return a value for an item that does not exist in a dictionary.
A Python dictionary is a set of key-value pairs that are stored within curly braces ({}):
raspberry_pi = { "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" }
The keys are “name”, “price”, and “RAM”. Keys appear before a colon in a dictionary.
Let’s see what happens if we try to retrieve the number of USB ports in our dictionary:
print(raspberry_pi["usb_ports"])
Our code returns:
KeyError: 'usb_ports'
This error tells us the key we have specified does not exist. In this case, the missing key is “usb_ports”.
KeyError Python: Solutions
To handle a Python dictionary KeyError you can:
- Check for a key in advance using indexing
- Use the “in” keyword to check for a key
- Use a try…except block.
The solution to handle the KeyError that works best for you will vary depending on your use case.
Use the Dictionary get() Method
The Python dictionary get() method returns a value in a dictionary. You can specify a default value with the get() method. This default value is returned if the name of the key you have specified does not have a value.
Consider the following code:
raspberry_pi = { "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" } get_key = input("What information would you like to retrieve (name, price, RAM)? ") print("The {} for this computer is {}.".format(get_key, raspberry_pi.get(get_key, "not available"))
Let’s run our code using the Python interpreter and see what happens:
What information would you like to retrieve? ALU The ALU for this computer is not available.
Our code uses the dictionary get() method to retrieve “ALU” from our dictionary. No value corresponds with this key name. The get() method returns the default value we have specified, which is “not available”.
Check for a Key in Advance Using Indexing
You can check for the existence of a key using indexing to avoid encountering a KeyError. If a key is in a dictionary, you can use that key. Otherwise, you can instruct your program to do something else that does not depend on that key.
Let’s write a program that accesses keys in our “raspberry_pi” dictionary in Python. Let’s check if our key is in our dictionary using indexing:
raspberry_pi = { "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" } get_key = input("What information would you like to retrieve (name, price, RAM)? ") if raspberry_pi[get_key]: print("The {} for this computer is {}.".format(get_key, raspberry_pi[get_key])) else: print("This information is not available.")
We have used a Python “if” statement to check if our key exists. “raspberry_pi[get_key]” will only return a value if the key exists. This means that if our key exists, our “if” statement will execute. If our key does not exist, the “else” statement will execute.
Let’s try to find out the RAM for our Raspberry Pi:
What information would you like to retrieve (name, price, RAM)? RAM The RAM for this computer is 4GB.
Now, let’s try to find out about how many USB ports the computer has:
What information would you like to retrieve (name, price, RAM)? USB This information is not available.
Our code does not raise a KeyError! This is because we’ve checked if our key exists first before using it. If we had used raspberry_pi[get_key] inside our “else” statement, our code would return a KeyError.
Using a try…except Block
A Python try…except block will try to run a line of code. If that line of code cannot be run, our code will raise a custom error according to the exceptions you have stated.
We can use a try…except block to determine the existence of an error and stop an unexpected KeyError from helping our Python program.
Let’s define a custom error for our computer example from earlier using a try…except block:
raspberry_pi = { "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" } get_key = input("What information would you like to retrieve (name, price, RAM)? ") try: print("The {} for this computer is {}.".format(get_key, raspberry_pi[get_key])) except KeyError: print("This information is not available.")
We use a try…except block to try to print out a particular piece of information about the Raspberry Pi computer to the console. If our code raises a KeyError anywhere in the “try” block, our code executes the contents of the “except” block.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
This means that every time a KeyError is raised, “This information is not available” is printed to the console. Let’s try to find out about the computer’s name:
What information would you like to retrieve (name, price, RAM)? name The name for this computer is Raspberry Pi 4.
Now, let’s try to learn about the computer’s USB port availability:
What information would you like to retrieve (name, price, RAM)? USB This information is not available.
Our code raises a KeyError inside our “try” block. This causes our code to execute the “except” block of code.
Check for a Key in Advance Using in
The “in” keyword is one of Python’s membership operators. It checks if an item is in a list of values. You can use the “in” keyword to check if a key is inside a dictionary.
This program will check if a key exists before printing out its value to the console:
raspberry_pi = { "name": "Raspberry Pi 4", "price": 35.00, "RAM": "4GB" } get_key = input("What information would you like to retrieve (name, price, RAM)? ") if get_key in raspberry_pi: print("The {} for this computer is {}.".format(get_key, raspberry_pi[get_key])) else: print("This information is not available.")
This code will check if the value of “get_key” is a key inside the “raspberry_pi” dictionary. If the key exists, the “if” statement will run. Otherwise, the “else” statement will run. Let’s try to check for information about the computer’s CPU:
What information would you like to retrieve (name, price, RAM)? CPU This information is not available.
Let’s check for the name of the computer:
What information would you like to retrieve (name, price, RAM)? name The name for this computer is Raspberry Pi 4.
Our code works! When we search for a key that does not exist, the “else” statement runs. This means that no KeyError can be raised in our code because we do not attempt to access a key in the “else” block.
Our code works! When we search for a key that does not exist, the “else” statement runs. This means that no KeyError can be raised in our code because we do not attempt to access a key in the “else” block.
Conclusion
A KeyError is raised when you try to access a value from a dictionary that does not exist. To solve a key error, you can check for a key upfront before using it and only use it if the key exists. You can use a try…except block to handle a key error.
For advice on how to learn the Python programming language, check out our comprehensive How to Learn Python guide. You’ll find links to top learning resources, books, and courses in this guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.