Creating tree structures with lambda expression and defaultdict

Viewed 108

The below code example uses a recursive definition. To my understanding, whenever a key is defined, its corresponding value is set as a dictionary as default. This way of definition allows arbitrary depth.

import collections
tree = lambda: collections.defaultdict(tree)
some_dict = tree()
some_dict['color']['favor'] = "yellow"

However, I do not understand why not defining as the following way:

import collections
tree = collections.defaultdict(collections.defaultdict)

It seems both way work correctly. They both allow defining dictionary of arbitrary depth. Are they different in any sense?

1 Answers

They are far from equivalent in that the second one does not create arbitrary nesting depth:

from collections import defaultdict

tree = lambda: defaultdict(tree)

some_dict_1 = tree()
some_dict_2 = defaultdict(defaultdict)

Now, check out some deeper access:

>>> some_dict_1[1][2][3][4] = 5  # works fine
>>> some_dict_2[1][2][3][4] = 5
KeyError: 2

Also note that a plain defaultdict as default factory isn't worth much more than a simple dict as it will create missing values as defaultdict(), i.e. without a default factory of its own:

>>> some_dict_2[1][2]
KeyError: 2

even though some_dict_2[1] is a defaultdict ("by name, not by game"):

>>> some_dict_2[1]
defaultdict(None, {})
Related