KeyError

noun

say it: “KEE AIR-er” /ˈki ˈɛrər/

The error Python reports when a program asks a dictionary for a key that isn't in it; the message shows the missing key.

What is a KeyError?

A KeyError is the error Python raises when you ask a dictionary for a key it doesn't have. The message names the missing key; get() or a check with in avoids it.

prices = {"latte": 4.25, "mocha": 4.75}
print(prices["chai"])
# KeyError: 'chai'

In a sentence

  • “To avoid a KeyError, the code checks whether the student's name is in the grades first.”
  • “Looking up 'chai' on the menu raised a KeyError, because the menu had no chai yet.”

Level: Apprentice · More Python terms at this level

Updated