Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python KeyError

Reference for Python KeyError: why a missing dictionary key raises it, how to avoid it with get(), in and defaultdict, and how to catch and handle it.

KeyError is raised when you look up a key that is not in a mapping, most often a dictionary. The exception's argument is the missing key, so the message shows the key itself: KeyError: 'email'.

KeyError is a subclass of LookupError, as is IndexError, so one except LookupError handles a missing key or a bad index.

Python
user = {"name": "Ada"}
user["email"]   # KeyError: 'email'

Try it

Python Raising and handling KeyError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Avoiding KeyError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
value = mapping[key]          # raises KeyError if key is missing

try:
    ...
except KeyError as error:
    missing = error.args[0]
Name Description
args[0] The key that was not found.

Raises when: subscripting, pop(key), del or popitem() (on an empty dict) uses a key or state with no match.

Usage notes

  • Use dict.get(key, default) for a lookup with a fallback; it never raises and returns None when no default is given.
  • Test with in when you only need to know whether a key exists: if key in d:. For a check followed by a lookup, try/except KeyError avoids searching twice.
  • defaultdict, Counter and setdefault() create missing entries automatically, so counting and grouping code never raises.
  • Key types matter. 1, "1" and 1.0 are different keys apart from 1 == 1.0, which hash alike. Strings read from files or input often need int() before lookup.
  • Case and whitespace differences are a frequent cause: "Name" is not "name".
  • Nested data: data["user"]["email"] fails at whichever level is missing. Chain get() calls with {} defaults, or catch KeyError.
  • Not only dicts. os.environ, shelve, sys.modules, pandas labels and __missing__ methods also raise it. A dict subclass can define __missing__(self, key) to supply values.
  • set.remove(x) raises KeyError too; set.discard(x) does not.
  • Message detail. str(KeyError('a')) shows the key with quotes, unlike most exceptions; use error.args[0] when you need the bare key.