Python Principles

Python KeyError

This error means that you're trying to access an invalid key in a dictionary. This is typically because the key does not exist in the dictionary.

In other words, there is no key/value pair corresponding to the key you used in the dictionary.

Perhaps you misspelled the key, or forgot to put it into the dictionary.

Here is an example of triggering a KeyError:

d = {1: 2}
print(d[3])

This gives the following error:

Traceback (most recent call last):
  File "/tmp/pyrunner1pFb7VrU/code.py", line 3, in
    print(d[3])
KeyError: 3

Note that Python shows you the offending line. It also gives you the invalid key that you tried to use.

It can be helpful to print the dictionary right before you index into it, to see if the key you expect to be there is truly there.

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges