Python Glossary Русский

all Python 3Exceptionsexception

KeyError

built-in exceptions

Raised when a dictionary key that does not exist is accessed. Use .get() to avoid it.

Syntax

raise KeyError(key)

The exception carries only the key itself, so print(e) shows 'b' in quotes and nothing more — a human-readable message is on you. And .get() is not always the fix: when the key is supposed to be there, a silent default just hides a typo and blows up later somewhere else. The same KeyError is also raised by set.remove().

Examples

d = {'a': 1}
d['b']               # KeyError: 'b'
d.get('b', 0)        # 0 — безопасно
try:
    v = d['x']
except KeyError:
    v = None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy