Chapters
Python114 chapters

ReferenceDictionary methods

dict.setdefault()

Returns the value, creating it from the default first if the key is missing.

Signature

mapping.setdefault(key, default=None)

Parameters

NameMeans
keywhat to look up
defaultwhat to store when it is absent

Returns

The existing or newly created value.

Example

Python
groups = {}
groups.setdefault("maths", []).append("ada")
groups.setdefault("maths", []).append("grace")
print(groups)

Output

{'maths': ['ada', 'grace']}

See also