3

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) ) )
Community
  • 1
  • 1
Magellan88
  • 2,543
  • 3
  • 24
  • 36

2 Answers2

6
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
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

You can also do this iteratively with a for loop building from the inside outward:

def Gen_DDict(dim=3, inner_factory=int):
    factory = defaultdict(inner_factory)

    def get_factory(z):
        def factory_func():
            return z
        return factory_func

    for i in range(dim-1):
        factory = defaultdict(get_factory(factory))

    return factory
lemonhead
  • 5,328
  • 1
  • 13
  • 25