Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nesting defaultdicts in an arbitrary depth

Tags:

python

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) ) )
like image 950
Magellan88 Avatar asked Mar 24 '26 04:03

Magellan88


1 Answers

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
like image 93
inspectorG4dget Avatar answered Mar 25 '26 19:03

inspectorG4dget



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!