2

I am looking for a way to define a collections.defaultdict (factory) that returns for each key in arbitrary depth again a defaultdict.

E.g.,

  foo = collections.defaultdict(lambda: *magic with defaultdict* )

so that

>>>> foo['bar']
defaultdict(<function lambda --> defaultdict,...)
>>> foo['bar']['baz']
defaultdict(<function lambda --> defaultdict,...)

ad infinitum.

I tried something more baroque with a deepcopy of a lambda-defaultdict as lambda of the 'actual' defaultdict

>>> fooDict = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict()))
>>> barDict = collections.defaultdict(lambda: collections.defaultdict(lambda: copy.deepcopy(fooDict)))

but which fails miserably in the forth generation (not surprisingly, when thinking through).

THX
  • 553
  • 2
  • 8
  • 18
  • 1
    hmmmm You could create class whichimplements `x.__getitem__(key)` and then when object under the `key` exists return it , when not just return new instance of this same class. – Take_Care_ Jun 22 '18 at 12:42
  • I went now for @BrenBarn answer tree = lambda: defaultdict(tree) ; foo = tree() in https://stackoverflow.com/questions/19189274/defaultdict-of-defaultdict-nested – THX Jun 22 '18 at 12:50

0 Answers0