I would like to nest an arbitrary number of defaultdicts like so:
from collections import defaultdict
D = defaultdict( lambda:defaultdict(int) )
this works fine as described earlier.
Now I'm looking for the way/function to do this for an arbitrary depth: so for instance I'd like to have a function
def Gen_DDict( dim=3 ):
"code I'm looking for"
that will return this for dim=3:
defaultdict( lambda : defaultdict( lambda : defaultdict(int) ) )
def genDDict(dim=3):
if dim==1:
return collections.defaultdict(int)
else:
return collections.defaultdict(lambda: genDDict(dim-1))
Output:
In [257]: d = genDDict(2)
In [258]: d[2][1]
Out[258]: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With