0Pricing
Python Academy · Lesson

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

  1. Counter
  2. defaultdict
  3. deque
  4. namedtuple and OrderedDict
← Back to Python Academy