dict · Python
d[key]
Returns the value for a key; raises KeyError if it is missing.
d[key]
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Assumes: Good hash distribution.
One hash and a short probe sequence.
Tested example
ages = {"ada": 36}
assert ages["ada"] == 36
try:
ages["nobody"]
raise AssertionError("expected KeyError")
except KeyError:
pass
Parameters
- key
- The key.
Behaviour
- Returns
- The value.
- Errors and preconditions
- KeyError if missing (a dict subclass can define __missing__ instead, as defaultdict does).
- Changes
- Nothing.
- Memory and invalidation
- No allocation.