Technical skill practice
Key Error in Python: Missing Keys vs Present None Values
Python raises KeyError when a mapping lookup asks for a key that is absent. That is different from a key whose stored value is None. With nested dictionaries, identify which level failed instead of treating every missing field as the same error or suppressing the entire operation.
Start with a small, explicit task
Inspect a fictional location record whose city field is present but unknown and whose postal field is absent. Check membership, direct lookup and get with an explicit sentinel. Keep required-field handling separate from an optional-value display rule.
Run the complete example
This original example was checked with Python 3.12.14. Save it as python_key_error.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.
Expected output
city present: True value: None
missing key: postal
record = {"location": {"city": None}}
location = record["location"]
missing = object()
assert "city" in location and location["city"] is None
assert "postal" not in location
assert location.get("city", missing) is None
assert location.get("postal", missing) is missing
try:
location["postal"]
except KeyError as exc:
absent_key = exc.args[0]
else:
raise AssertionError("expected missing key")
assert absent_key == "postal"
print("city present:", "city" in location, "value:", location["city"])
print("missing key:", absent_key)
Explain the result
Direct city lookup succeeds even though its value is None. The postal lookup fails because no such key exists. A plain get without an explicit default would return None for the absent key too, making the two situations look alike. The unique object sentinel preserves the distinction using identity checks.
The targeted except records the missing key from the error’s arguments. That is useful when explaining the failing field without turning every exception into a default record. In a deeper structure, an absent location key would fail at an earlier lookup; a location value of None would raise a different type-related error when used like a dictionary.
Avoid these mistakes
Use defaults only when they represent an actual allowed absence, not to conceal a broken required-data contract. Avoid checking only truthiness: an empty string or numeric zero can be present, legitimate values. Keep error messages free of unnecessary private record contents when adapting this pattern.
Questions, answered
Does a None value raise KeyError?
Not when the key exists. The checked city lookup returns its stored None normally.
Why use a sentinel with get?
It lets the caller distinguish an absent key from a present key whose value is None.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.