dict · Python
d[key] = value / setdefault
Adds a key or replaces its value; setdefault adds only when missing.
d[key] = value; dict.setdefault(key, default=None, /)
Complexity
| Average | O(1) |
|---|---|
| Amortized | O(1) including resizes |
| Worst case | O(n) |
| Extra space | O(1) amortized |
Assumes: Hashes spread well; the worst case needs many collisions.
Hash the key, probe the index table for a free or matching slot, append to the entries array. Resizing rebuilds the table occasionally.
Tested example
ages: dict[str, int] = {}
ages["ada"] = 36 # adds
ages["ada"] = 37 # replaces: keys are unique
ages["bob"] = 25
assert ages == {"ada": 37, "bob": 25}
assert list(ages) == ["ada", "bob"] # insertion order is guaranteed (3.7+)
ages.setdefault("cy", 41) # adds only if missing
Parameters
- key
- Any hashable object.
Behaviour
- Returns
- Assignment: nothing. setdefault: the value now stored.
- Errors and preconditions
- TypeError for an unhashable key.
- Changes
- Adds or replaces one entry; may resize.
- Memory and invalidation
- May resize. Invalidates running iterators (RuntimeError if the size changes).