What does KeyError mean in Python?

Updated October 2026 · How we answer

Short answerA KeyError means you tried to read a dictionary key that does not exist. Check the key name, confirm it is in the dictionary, or use a safe lookup method like get.

Why the error happens

Python raises KeyError when code uses square brackets to read a key that is not in a dictionary, such as data['email'] when the dictionary has no email entry. The message usually shows the missing key name in quotes, which is the first clue to where the problem is.

Common causes include a typo in the key, a key that only exists in some records, or data that came from an API or file in a different shape than you expected. Printing the dictionary's keys just before the failing line often reveals the mismatch quickly.

  • Print list(data.keys()) before the failing line
  • Check for typos and letter case differences
  • Confirm the source data really contains that field

How to fix it

Use data.get('email') when a missing key is acceptable, since it returns None instead of raising an error. You can also supply a default, such as data.get('email', ''). Use an if 'email' in data check when the missing key needs a different path.

If the key should always exist, let the error stay visible so you find the source problem. Hiding it with a default can cause quiet bugs further downstream.

Dictionaries in JSON data often include nested objects, so the key may exist one level deeper than you expect. Printing the full structure with a quick look is faster than guessing.

Common mistakes

  • Wrapping the whole block in try except and ignoring the error.
  • Using get everywhere without checking why a required key is missing.
From our shopsCASEONYX: Dark-luxe tough phone cases.