Variable from dictionary key

I have a dictionary and I want to extract a value from the dictionary and hand it over to a variable. The problem is: when I give the value from the dictionary to the variable and add a value to the variable (in the way I did it in the following example) my Dictionary changes too.
But I don’t want to change the value of the variablekey in the dictionary.

dict=Dict{Any,Any}((0) => [1],(1) =>[2], (2) => [3],(3) =>  [4])
y = append!(dict[ ( 0 ) ], [1])
println("variable y is ", y)
print("dict should not change but it changed to: ", dict)

Thanks for help.

This behavior is more due to the nature of arrays than to the fact that they are in a Dict. Arrays are passed by reference. If you want a distinct storage area you should copy the array.

2 Likes

This is a way it works indeed:


dict=Dict{Any,Any}((0) => [1],(1) =>[2], (2) => [3],(3) =>  [4])
println("dict is ", dict)
y = dict[ ( 1 ) ]
println("y is ", y)
h=copy(y)
h = append!(h, [2])
println("h is ", h)
println("dict doesn't change: ", dict)

A shorter way would be using vcat (vertical concatenation, as one-dimensional arrays are considered “columns” in Julia):

dict=Dict{Any,Any}((0) => [1],(1) =>[2], (2) => [3],(3) =>  [4])
y = vcat(dict[(0)], [1])

The nice thing is that vcat can take both scalar and vector arguments, so that

y = vcat(dict[(0)], 1)

will just do the same.
Also, [a; b] is syntactic sugar for vcat(a, b), so the above can even be written as

y = [dict[(0)]; 1] # or [dict[(0)]; [1]]
2 Likes