Thursday, October 24, 2013

Python: defaultdict of defaultdict

Recently I was trying to create a nested dict (or better nested defaultdict) in Python. This is the solution that matched my needs perfectly:

 from collections import defaultdict
nested_dict = defaultdict(lambda : defaultdict(list))

The defaultdict constructor takes any factory as an argument, a requirement that can be easily be met using python lambda functions.