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

← All Python dict methods · String methods · Built-in functions