dict · Python
get
Returns the value, or a default when the key is missing, without raising.
dict.get(key, default=None, /)
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Same lookup as d[key].
Tested example
ages = {"ada": 36}
assert ages.get("ada") == 36
assert ages.get("nobody") is None # no exception
assert ages.get("nobody", 0) == 0 # explicit default
Parameters
- key
- The key.
- default
- Returned when missing (None if omitted).
Behaviour
- Returns
- The value or the default.
- Errors and preconditions
- TypeError for an unhashable key.
- Changes
- Nothing (it does not insert the default; setdefault does).
- Memory and invalidation
- No allocation.