CKTIS / Python
KeyError — missing mapping key
KeyError means that a requested key was not found in a mapping, such as a dict. Learn the difference between square-bracket lookup and get(), and handle missing keys without hiding unrelated errors.
Version: Python 3.14; repository image, production runtime not attested
Syntax
try:
value = mapping[key]
except KeyError:
...KeyError is a built-in exception derived from LookupError. It signals that a requested mapping key is missing. For a plain dict, mapping[key] raises this exception when the key does not exist. Do not confuse it with IndexError, which concerns an out-of-range sequence index.
If a missing key is expected, use try / except KeyError or mapping.get(key, default). For a dict, get() returns the default only when the key is absent; without an explicit default, it returns None in that case. An existing key whose value is None is not a missing key and does not trigger the default. The expression key in mapping tests key membership.
Keep the try block limited to the operation whose missing key you intend to handle, so you do not accidentally catch a KeyError from another call. If the key is required, correct the input or let the exception propagate rather than ignoring it unconditionally.
The example contrasts the missing "language" key with the existing "nickname" key holding None. Caveat: a dict subclass can define __missing__() to change how mapping[key] handles an absent key; get() does not invoke that mechanism.
Examples
settings = {"theme": "dark", "nickname": None}
try:
print(settings["language"])
except KeyError:
print("Missing key: language")
print(settings.get("language", "en"))
print(settings.get("nickname", "guest"))Result
Missing key: language en None
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.