dict.setdefault
Get the value for a key, and if the key is missing, add it with the value default.
Python 3.13
dict.setdefault(key[, default])Parameters
- keyHashable
- The key to look up.
- defaultAnyoptional
- The value for a new key.
Return value
The value of the key: the existing one or the newly added one.
Examples
Existing and new key
Python 3.13
a = {'x': 1}
print(a.setdefault('x', 5))
print(a.setdefault('y', 2))
print(a)1
2
{'x': 1, 'y': 2}Grouping words by first letter
Python 3.13
groups = {}
for word in ['apple', 'avocado', 'banana']:
groups.setdefault(word[0], []).append(word)
print(groups){'a': ['apple', 'avocado'], 'b': ['banana']}Details
The value of an existing key is not changed. For grouping, collections.defaultdict is more convenient.
