liveBook · Manning

KeyError

As explained in Python How-To

KeyError is the Python exception raised when a mapping is accessed with a key that is not present.

KeyError is raised when dictionary subscript notation requests a key that is absent. Without try...except handling, the exception can crash the program. section 3.4.2

A missing task key

urgencies = {"Laundry": 3, "Homework": 5} urgencies["Homeworks"] # KeyError: 'Homeworks' section 3.4.2

Choose the response according to whether a missing key signals bad input or an expected absence:

  • Check membership before indexing when the key may be absent: if "Homework" in urgencies: urgency = urgencies["Homework"] else: urgency = "N/A". section 3.4.3
  • Extract a repeated check into a function, but avoid hardcoding one dictionary and one meaning when the pattern must serve multiple mappings. section 3.4.3
  • Use the get method for concise fallback behavior when absence is acceptable, but remember that it can hide misspelled keys. section 3.4.3 section 3.4.6
  • Keep subscript notation when an absent key represents a defect that should surface during development. section 3.4.6
urgencies["Homeworks"]
# ERROR: KeyError: 'Homeworks'

Inspect the misspelled dictionary access and its KeyError result. section 3.4.2

How Python How-To covers it

How deep it goes
Explains the missing-key cause, crash consequence, membership-check workaround, repetition trade-off, and get-method visibility trade-off.
Examples
Demonstrates KeyError with an urgencies dictionary and the misspelled key "Homeworks".
What it assumes
Assumes dictionaries and square-bracket access, while explaining how dictionary keys identify values and trigger lookup errors.
What you can do after
Diagnose missing dictionary keys and select a maintainable access pattern that either supplies a fallback or exposes defects.
How it connects
Connects KeyError with dictionaries, subscript notation, try...except, the get method, and the DRY principle.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.