What is KeyError in Python? Dictionary and Handling Them

What is KeyError in Python? Dictionary and Handling Them

image 11 1

What a Python KeyError Usually Means

A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict).

Python’s official documentation says that the KeyError is raised when a mapping key is accessed and isn’t found in the mapping. A mapping is a data structure that maps one set of values to another. The most common mapping in Python is the dictionary.

The Python KeyError is a type of LookupError exception and denotes that there was an issue retrieving the key you were looking for. When you see a KeyError, the semantic meaning is that the key being looked for could not be found.

In the example below, you can see a dictionary (ages) defined with the ages of three people. When you try to access a key that is not in the dictionary, a KeyError is raised:


>>> ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33}>>> ages['Michael']Traceback (most recent call last):
  File "<stdin>", line 1, in <module>KeyError: 'Michael'

Here, attempting to access the key 'Michael' in the ages dictionary results in a KeyError being raised. At the bottom of the traceback, you get the relevant information:

  • The fact that a KeyError was raised
  • The key that couldn’t be found, which was 'Michael'

The second-to-last line tells you which line raised the exception. This information is more helpful when you execute Python code from a file.

Note: When an exception is raised in Python, it is done with a traceback. The traceback gives you all the relevant information to be able to determine why the exception was raised and what caused it.

Learning how to read a Python traceback and understanding what it is telling you is crucial to improving as a Python programmer. To learn more on Python tracebacks, check out Understanding the Python Traceback

In the program below, you can see the ages dictionary defined again. This time, you will be prompted to provide the name of the person to retrieve the age for:

 1# 2 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33} 4person = input('Get age for: ') 5print(f'{person} is {ages[person]} years old.')

This code will take the name that you provide at the prompt and attempt to retrieve the age for that person. Whatever you type in at the prompt will be used as the key to the ages dictionary, on line 4.

Repeating the failed example from above, we get another traceback, this time with information about the line in the file that the KeyError is raised from:

$ python
Get age for: MichaelTraceback (most recent call last):File "", line 4, in <module>  print(f'{person} is {ages[person]} years old.')KeyError: 'Michael'

The program fails when you give a key that is not in the dictionary. Here, the traceback’s last few lines point to the problem. File "", line 4, in <module> tells you which line of which file raised the resulting KeyError exception. Then you are shown that line. Finally, the KeyError exception provides the missing key.

So you can see that the KeyError traceback’s final line doesn’t give you enough information on its own, but the lines before it can get you a lot closer to understanding what went wrong.

Note: Like the example above, most of the other examples in this tutorial make use of f-strings, which were introduced in Python 3.6.

Where Else You Might See a Python KeyError in the Standard Library

The large majority of the time, a Python KeyError is raised because a key is not found in a dictionary or a dictionary subclass (such as os.environ).

In rare cases, you may also see it raised in other places in Python’s Standard Library, such as in the zipfile module, if an item is not found in a ZIP archive. However, these places keep the same semantic meaning of the Python KeyError, which is not finding the key requested.

In the following example, you can see using the zipfile.ZipFile class to extract information about a ZIP archive using .getinfo():


>>> from zipfile import ZipFile>>> zip_file = ZipFile('')>>> zip_file.getinfo('something')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/path/to/python/installation/", line 1304, in getinfo  'There is no item named %r in the archive' % name)KeyError: "There is no item named 'something' in the archive"

This doesn’t really look like a dictionary key lookup. Instead, it is a call to zipfile.ZipFile.getinfo() that raises the exception.

The traceback also looks a little different with a little more information given than just the missing key: KeyError: "There is no item named 'something' in the archive".

The final thing to note here is that the line that raised the KeyError isn’t in your code. It is in the zipfile code, but previous lines of the traceback indicate which lines in your code caused the problem.

When You Need to Raise a Python KeyError in Your Own Code

There may be times when it makes sense for you to raise a Python KeyError exception in your own code. This can be done by using the raise keyword and calling the KeyError exception:

raise KeyError(message)

Usually, the message would be the missing key. However, as in the case of the zipfile package, you could opt to give a bit more information to help the next developer better understand what went wrong.

If you decide to raise a Python KeyError in your own code, just make sure that your use case matches the semantic meaning behind the exception. It should denote that the key being looked for could not be found.

How to Handle a Python KeyError When You See It

When you encounter a KeyError, there are a few standard ways to handle it. Depending on your use case, some of these solutions might be better than others. The ultimate goal is to stop unexpected KeyError exceptions from being raised.

The Usual Solution: .get()

If the KeyError is raised from a failed dictionary key lookup in your own code, you can use .get() to return either the value found at the specified key or a default value.

Much like the age retrieval example from before, the following example shows a better way to get the age from the dictionary using the key provided at the prompt:

 1# 2 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33} 4person = input('Get age for: ') 5age = ages.get(person) 6 7if age: 8    print(f'{person} is {age} years old.') 9else:10    print(f"{person}'s age is unknown.")

Here, line 5 shows how you can get the age value from ages using .get(). This will result in the age variable having the age value found in the dictionary for the key provided or a default value, None in this case.

This time, you will not get a KeyError exception raised because of the use of the safer .get() method to get the age rather than attempting to access the key directly:

$ python
Get age for: MichaelMichael's age is unknown.

In the example execution above, the KeyError is no longer raised when a bad key is provided. The key 'Michael' is not found in the dictionary, but by using .get(), we get a None returned rather than a raised KeyError.

The age variable will either have the person’s age found in the dictionary or the default value (None by default). You can also specify a different default value in the .get() call by passing a second argument.

This is line 5 from the example above with a different default age specified using .get():

age = ages.get(person, 0)

Here, instead of 'Michael' returning None, it would return 0 because the key isn’t found, and the default value to return is now 0.

The Rare Solution: Checking for Keys

There are times when you need to determine the existence of a key in a dictionary. In these cases, using .get() might not give you the correct information. Getting a None returned from a call to .get() could mean that the key wasn’t found or that the value found at the key in the dictionary is actually None.

With a dictionary or dictionary-like object, you can use the in operator to determine whether a key is in the mapping. This operator will return a Boolean (True or False) value indicating whether the key is found in the dictionary.

In this example, you are getting a response dictionary from calling an API. This response might have an error key value defined in the response, which would indicate that the response is in an error state:

 1# 2... 3# Assuming you got a `response` from calling an API that might 4# have an error key in the `response` if something went wrong 5 6if 'error' in response: 7    ...  # Parse the error state 8else: 9    ...  # Parse the success state

Here, there is a difference in checking to see if the error key exists in the response and getting a default value from the key. This is a rare case where what you are actually looking for is if the key is in the dictionary and not what the value at that key is.

The General Solution: try except

As with any exception, you can always use the tryexcept block to isolate the potential exception-raising code and provide a backup solution.

You can use the tryexcept block in a similar example as before, but this time providing a default message to be printed should a KeyError be raised in the normal case:

 1# 2 3ages = {'Jim': 30, 'Pam': 28, 'Kevin': 33} 4person = input('Get age for: ') 5 6try: 7    print(f'{person} is {ages[person]} years old.') 8except KeyError: 9    print(f"{person}'s age is unknown.")

Here, you can see the normal case in the try block of printing the person’s name and age. The backup case is in the except block, where if a KeyError is raised in the normal case, then the backup case is to print a different message.

The tryexcept block solution is also a great solution for other places that might not support .get() or the in operator. It is also the best solution if the KeyError is being raised from another person’s code.

Here is an example using the zipfile package again. This time, the tryexcept block gives us a way to stop the KeyError exception from stopping the program:


>>> from zipfile import ZipFile>>> zip = ZipFile('')>>> try:...     zip.getinfo('something')... except KeyError:...     print('Can not find "something"')...Can not find "something"

Since the ZipFile class does not provide .get(), like the dictionary does, you need to use the tryexcept solution. In this example, you don’t have to know ahead of time what values are valid to pass to .getinfo().


You now know some common places where Python’s KeyError exception could be raised and some great solutions you could use to prevent them from stopping your program.

Now, the next time you see a KeyError raised, you will know that it is probably just a bad dictionary key lookup. You will also be able to find all the information you need to determine where the error is coming from by looking at the last few lines of the traceback.

If the problem is a dictionary key lookup in your own code, then you can switch from accessing the key directly on the dictionary to using the safer .get() method with a default return value. If the problem isn’t coming from your own code, then using the tryexcept block is your best bet for controlling your code’s flow.

Exceptions don’t have to be scary. Once you know how to understand the information provided to you in their tracebacks and the root cause of the exception, then you can use these solutions to make your programs flow more predictably.

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar

Subscribe to Newsletter

Stay ahead of the rapidly evolving world of technology with our news letters. Subscribe now!