Dictionary Access and Missing Keys
Core idea
Use d[key] when a key must exist. In an ordinary dictionary a missing key raises KeyError. Use d.get(key, default) when absence is expected; it returns the default without adding an entry. If the default is omitted it is None. Test key in d to distinguish absence from a stored None.
Direct access returns the value.
Use an explicit fallback
stock = {"tea": 0}print(stock.get("tea", 99))print(stock.get("milk", 99))print(len(stock))Zero is an existing value; the fallback applies only to absence and does not insert.
Distinguish None and absence
details = {"room": None}print(details.get("room"), details.get("floor"))print("room" in details, "floor" in details)The returned values match but only room is present.
Common mistake
d.get(key) or 10 also substitutes 10 for stored zero or empty text. Use get with an explicit default when only missing keys should trigger the fallback.
Practice
Look up a missing product with a fallback of zero, then verify that the product was not inserted.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Missing keys and lookup
Check your understanding of access and missing keys.
What is printed?
print({"a": 0}.get("a", 5))What is printed?
d = {}d.get("x", 0)print("x" in d)What is printed?
print("x" in {"x": None})Which operation raises KeyError for a missing key in an ordinary dict?