defaultdict helps to reduce boilerplate code in Python. Using it in normal circumstances is very easy:
from collections import defaultdict default_int_dict = defaultdict(int) default_int_dict['a'] += 1 assert default_int_dict['a'] == 1 default_int_dict['a'] += 1 assert default_int_dict['a'] == 2
But how to use it with nested arrays ? For instance you can add a generator as default value:
default_int_nested_dict = defaultdict(lambda: defaultdict(int)) default_int_nested_dict['a'][1] += 1 assert default_int_nested_dict['a'][1] == 1 default_int_nested_dict['a'][1] += 1 assert default_int_nested_dict['a'][1] == 2