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
| Parameter | Description |
|---|---|
key |
The key. |
default optional |
Inserted and returned if the key is missing. Default: None |
Return value
The existing or newly inserted value.
Examples
groups = {}
for name in ["Ada", "Alan", "Bob"]:
groups.setdefault(name[0], []).append(name)
print(groups)
Output
{'A': ['Ada', 'Alan'], 'B': ['Bob']}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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dict.get()· Return the value for a key, or a default (None unless given) if the key is missing, without raising KeyError.dict.fromkeys()· Create a new dictionary with the given keys, all set to the same value (None by default).dict.update()· Add or overwrite keys from another mapping, an iterable of pairs, or keyword arguments, in place.- Python Dictionaries · tutorial