Python tip: default dict
Jan 19, 2021
Sometimes you need to initialize dictionary before you use it, for this reason you can use dict() subclass defaultdict(). This is how you would do it normally.
# counter for cars by vendor
cars = dict()
if 'ferrari' not in cars:
cars['ferrari'] = 1
else:
cars['ferrari'] += 1
but with default dict this scenario is far easier
# counter for cars by vendor
from collections import defaultdict
cars = defaultdict(int)
cars['ferrari'] += 1
Always remember that defaultdict takes as parameter callable (function) not default value.