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.
user = {"name": "Ada"} user["email"] # KeyError: 'email'
Try it
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.
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
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 returnsNonewhen no default is given. - Test with
inwhen you only need to know whether a key exists:if key in d:. For a check followed by a lookup,try/except KeyErroravoids searching twice. defaultdict,Counterandsetdefault()create missing entries automatically, so counting and grouping code never raises.- Key types matter.
1,"1"and1.0are different keys apart from1 == 1.0, which hash alike. Strings read from files or input often needint()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. Chainget()calls with{}defaults, or catchKeyError. - Not only dicts.
os.environ,shelve,sys.modules,pandaslabels and__missing__methods also raise it. A dict subclass can define__missing__(self, key)to supply values. set.remove(x)raisesKeyErrortoo;set.discard(x)does not.- Message detail.
str(KeyError('a'))shows the key with quotes, unlike most exceptions; useerror.args[0]when you need the bare key.