defaultdict
Auto-initialize dictionary values.
The missing-key problem
With a normal dict, accessing a key that does not exist raises KeyError. This is annoying when you want to build up values incrementally.
d = {}
try:
d['x'].append(1)
except KeyError as e:
print('KeyError:', e)Enter defaultdict
defaultdict from collections takes a factory function that produces a default value for any missing key. Import it with from collections import defaultdict.
from collections import defaultdict
d = defaultdict(int)
print(d['missing'])
print(dict(d))All lessons in this course
- Counter
- defaultdict
- deque
- namedtuple and OrderedDict