access
dict.setdefault
If key is in the dictionary, returns its value. If not, inserts key with a value of default (None if omitted) and returns default.
d.setdefault(key[, default]) Parameters
| Parameter | Purpose |
|---|---|
| key | The key to look up or insert |
| default | Value to insert and return if key is missing (defaults to None) |
Examples
>>> d = {'a': 1}
>>> d.setdefault('a', 99)
1
>>> d
{'a': 1} Existing key: returns current value, does not overwrite
>>> d = {}
>>> d.setdefault('b', [])
[]
>>> d
{'b': []} Missing key: inserts default and returns it
>>> groups = {}
>>> for name, team in [('Ann','A'),('Bob','B'),('Cy','A')]:
... groups.setdefault(team, []).append(name)
>>> groups
{'A': ['Ann', 'Cy'], 'B': ['Bob']} Classic 'group-by' pattern — mutate the returned list in place
>>> d = {}
>>> d.setdefault('x')
>>> d
{'x': None} Omitting default inserts None
Gotcha
setdefault always evaluates the default argument even if key exists — use collections.defaultdict when the default is expensive to construct. It both modifies the dict and returns a value, unlike get.
Related methods
dict.get
Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None so this method never raises a KeyError.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict.fromkeys
Class method that builds a new dict whose keys come from iterable and whose values are all set to value (default None). The same value object is shared across every key — beware mutable defaults.
← All Python dict methods · String methods · Built-in functions