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}

This gives the following error:

Traceback (most recent call last):
  File "/tmp/pyrunner1pFb7VrU/", line 3, in
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.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!