Welcome, guest | Sign In | My Account | Store | Cart

A defaultdict that yields a defaultdict that yields a defaultdict, etc...

Python, 4 lines
1
2
3
4
from collections import defaultdict

f = lambda: defaultdict(f)
recursive_defaultdict = defauldict(f)

Other recipes for this often involve a ridiculous class definition with numerous overridden magic methods. YUCK. Do this instead.

1 comment

thom neale (author) 9 years, 9 months ago  # | flag

Another trick--you can set key paths of arbitrary depth like this:

from operator import getitem from collections import defaultdict

f = lambda: defaultdict(f) recursive_defaultdict = defauldict(f)

keypath = [1,2,3,4,3,2,3,4,5]

Set this keypath

reduce(getitem, [recursive_defaultdict] + keypath)

Someone could criticize this by saying "you could just set those keys with a loop. Explicit is better than implicit." To that I would say "yes, but flat is better than nested. And faster is better than slower."