Multiple levels of ‘collection.defaultdict’ in Python

Use:

from collections import defaultdict
d = defaultdict(lambda: defaultdict(int))

This will create a new defaultdict(int) whenever a new key is accessed in d.

Leave a Comment