Why does `dict.get()` return `None` when a key is missing?
Quick answer
dict.get(key) returns None when the key is absent; unlike my_dict[key], it does not raise KeyError for that missing key. You can provide a second argument, such as dict.get(key, "unknown"), to return your chosen default instead. But if the result is None, that alone cannot tell you whether the key was absent or present with a stored None; check membership when that distinction matters. [S1]
The question, the details, the next step.
A practical checklist
Decide whether the key is required or may be absent.
Use direct indexing when a missing key should raise
KeyError.Use
get(key, fallback)when absence should produce a chosen fallback.Check
key in dictionarywhen absence must differ from a storedNone.Try the pattern with both an absent key and a key whose value is
None.
A few more useful answers
What happens if I omit the default argument to `get()`?
If the key is absent and you provide no default, get() returns None. If you supply a default, it returns that value when the key is absent. [S1]
If I pass a default to `get()`, will it replace a stored `None`?
No. The specified default is returned when the key is absent. If the key exists with a stored value of None, the lookup returns that stored value. [S1]
When is direct indexing preferable?
Use direct indexing when the key is required and a missing key should raise KeyError. Use get() when absence is expected and you have a suitable fallback. [S1]
Sources
References used for this guide.
- [S1] Python 3.15 tutorial: dictionary lookup with get() docs.python.org · Checked
