all Python 3Dictionaries (dict)function
dict.setdefault
access
Return the value for a key; if absent, insert it with default and return default.
Syntax
d.setdefault(key, default=None)
The classic idiom is grouping: d.setdefault(k, []).append(x), since the method returns the very object stored in (or just placed into) the dictionary. The default is built on every call even when the key already exists — a fresh empty list is created and immediately discarded — so for heavy grouping collections.defaultdict(list) is cleaner and faster.
Examples
d = {'a': 1}
print(d.setdefault('a', 0)) # → 1
print(d.setdefault('b', 2)) # → 2
print(d) # → {'a': 1, 'b': 2}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy