The other answers here tell you how to create a defaultdict which contains “infinitely many” defaultdict, but they fail to address what I think may have been your initial need which was to simply have a two-depth defaultdict.
You may have been looking for:
defaultdict(lambda: defaultdict(dict))
The reasons why you might prefer this construct are:
- It is more explicit than the recursive solution, and therefore likely more understandable to the reader.
- This enables the “leaf” of the
defaultdictto be something other than a dictionary, e.g.,:defaultdict(lambda: defaultdict(list))ordefaultdict(lambda: defaultdict(set))