Imagine the following situation: you need to store something changeable in a dictionary as values, such as lists. And while working with this dictionary, you find yourself in a situation where you have a key and an element to add to the list, but the issue is that the key may not be in the dictionary. Here is the code you have to write:
if key not in dictionary:
dictionary[key] = [] # Initializing the list
dictionary[key].append(value) # Changing the list
It is not a particularly rare situation. The writers of the Python standard library also realized this and added the setdefault
method. We can rewrite the above code using this method:
dictionary.setdefault(key, []).append(value)
It is compact and concise. But what does the setdefault
method do? It takes a key and a default value and returns a reference to the value in the dictionary associated with the specified key. And if that key is not in the dictionary, then the method gives that key the default value and returns a reference to it. In the example above, the default value is an empty list []
.
The defaultdict
package
The standard Python package includes the collections module. Among other things, this module provides the defaultdict
type. The defaultdict
is an ordinary dictionary with one unique property — while a dictionary would tell you off for a missing key, the defaultdict
returns the default value. Let us look at an example:
from collections import defaultdict
d = defaultdict(int)
d['a'] += 5
d['b'] = d['c'] + 10
d # defaultdict(<class 'int'>, {'a': 5, 'c': 0, 'b': 10})