Education logo

What is KeyError in Python? Dictionary and Handling Them

What a Python KeyError Usually Means

By datacademy aiPublished 3 years ago 5 min read

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# ages.py 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 ages.py

Get age for: MichaelTraceback (most recent call last):File "ages.py", 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 "ages.py", 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('the_zip_file.zip')>>> zip_file.getinfo('something')Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/path/to/python/installation/zipfile.py", 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# ages.py 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.

For More Information: https://www.datacademy.ai/keyerror-in-python-dictonary-handling-datacademy/

Follow Us on:

YouTube: https://www.youtube.com/@datacademy-ai

Website: https://www.datacademy.ai/

LinkedIn: https://www.linkedin.com/company/datacademy-cloud/

Instagram: https://www.instagram.com/datacademy.ai/

Twitter: https://mobile.twitter.com/DatacademyAi

Facebook:https://www.facebook.com/people/Datacademyai/100086725062389

coursesinterviewstudentteacherhow to

About the Creator

datacademy ai

Datacademy.ai is an e-learning platform that aims to make education accessible to everyone, no matter where they are located. We believe that education is the key to unlocking one's potential and we are dedicated... see more

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2026 Creatd, Inc. All Rights Reserved.