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
