Understanding how nested defaultdict works

Hi,

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

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

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:

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!

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

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=>…
1 Like