Question: I have a large list like:

```
[A][B1][C1]=1
[A][B1][C2]=2
[A][B2]=3
[D][E][F][G]=4

```

I want to build a multi-level dict like:

```
A
--B1
-----C1=1
-----C2=1
--B2=3
D
--E
----F
------G=4

```

I know that if I use recursive defaultdict I can write `table[A][B1][C1]=1`, `table[A][B2]=2`, but this works only if I hardcode those insert statement. 

While parsing the list, I don't how many []'s I need beforehand to call `table[key1][key2][...]`.

Answer: 
You can do it without even defining a class:

```
from collections import defaultdict

nested_dict = lambda: defaultdict(nested_dict)
nest = nested_dict()

nest[0][1][2][3][4][5] = 6

```
You may achieve this with a recursive [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict).

```
from collections import defaultdict

def tree():
    def the_tree():
        return defaultdict(the_tree)
    return the_tree()

```

It is important to protect the default factory name, `the_tree` here, in a closure ("private" local function scope). Avoid using a one-liner `lambda` version, which is bugged due to Python's [late binding closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures), and implement this with a `def` instead.

The accepted answer, using a lambda, has a flaw where instances must rely on the `nested_dict` name existing in an outer scope. If for whatever reason the factory name can not be resolved (e.g. it was rebound or deleted) then pre-existing instances will also become subtly broken:

```
>>> nested_dict = lambda: defaultdict(nested_dict)
>>> nest = nested_dict()
>>> nest[0][1][2][3][4][6] = 7
>>> del nested_dict
>>> nest[8][9] = 10
# NameError: name 'nested_dict' is not defined

```