Python 3 reference · Dictionary Methods

Python Dictionary setdefault() Method

Return the value for a key; if the key is missing, insert it with a default value first and return that.

Python 3 Since 3.0

Syntax

dict.setdefault(key, default=None)

Parameters

ParameterDescription
key The key.
default optional Inserted and returned if the key is missing. Default: None

Return value

The existing or newly inserted value.

Examples

Group itemsTry it yourself
groups = {}
for name in ["Ada", "Alan", "Bob"]:
    groups.setdefault(name[0], []).append(name)
print(groups)

Output

{'A': ['Ada', 'Alan'], 'B': ['Bob']}
The defaultdict alternativeTry it yourself
from collections import defaultdict
groups = defaultdict(list)
for name in ["Ada", "Alan", "Bob"]:
    groups[name[0]].append(name)
print(dict(groups))

Output

{'A': ['Ada', 'Alan'], 'B': ['Bob']}

Version history

VersionChange
Python 3.0Added