# Understanding how nested defaultdict works

**URL:** <https://discourse.julialang.org/t/understanding-how-nested-defaultdict-works/78679>\
**Category:** New to Julia\
**Created:** [March 29, 2022, 2:01pm UTC](https://discourse.julialang.org/t/understanding-how-nested-defaultdict-works/78679 "2022-03-29T14:01:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![spragud2](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/spragud2/32/29409_2.png) [@spragud2](https://discourse.julialang.org/u/spragud2)\
**Post date:** [March 29, 2022, 2:01pm UTC](https://discourse.julialang.org/t/understanding-how-nested-defaultdict-works/78679/1 "2022-03-29T14:01:21Z")

</div>

Hi,

I wrote some code to recursively create nested defaultdicts to mimic a tree structure. Normally one would have to write something like

```julia
function tree()
    return DefaultDict(tree)
end

x = tree()
x[1][2][3]

```

To create an entry 1 =\> 2 =\> 3.

However I found some python code that I rewrote in Julia to take a list [1,2,3] and use it to insert into the tree

```julia
function insert(tree,nodes)
    for node ∈ nodes
        tree = tree[node]
    end
end

x = tree()
insert(x,[1,2,3])

```

My question is, why does this work?

I tried writing a for loop outside of a function call, like:

```julia
x = tree()
for i in [1,2,3]
x = x[i]
end 

```

but this doesn’t work. My question is why

Any understanding would be great!

---

<div class="post-metadata">

**Author:** ![MarcMush](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marcmush/32/18006_2.png) [@MarcMush](https://discourse.julialang.org/u/MarcMush)\
**Post date:** [March 29, 2022, 3:04pm UTC](https://discourse.julialang.org/t/understanding-how-nested-defaultdict-works/78679/2 "2022-03-29T15:04:39Z")

</div>

your last example is a scope issue, you’re losing the reference of the original `x`

```julia-repl
julia> t=tree()
DefaultDict{Any, Any, typeof(tree)}()

julia> let x=t
           for i in [1,2,3]
               x=x[i]
           end
       end

julia> t
DefaultDict{Any, Any, typeof(tree)} with 1 entry:
  1 => DefaultDict{Any, Any, typeof(tree)}(2=>DefaultDict{Any, Any, typeof(tree)}(3=>…

```
