Karin Dekel
Karin Dekel

Reputation: 33

Setting values to a specific element in an array of dictionary overrides all values in array

I'm trying to assign a specific value to a specific location in an array of dictionaries. the assignment overrides all values in array - why?

a = fill(Dict("example" => 0.),3)
a[1]["example"] = 1.
println(a)

''' output is

[Dict("example" => 1.0), Dict("example" => 1.0), Dict("example" => 1.0)]

Upvotes: 3

Views: 57

Answers (1)

ginkul
ginkul

Reputation: 1066

This is the expected behavior of fill and it's described in documentation.

If x is an object reference, all elements will refer to the same object

Use a Array comprehension

I suggest using array comprehension for this purpose.

julia> a = [Dict("example" => 0.) for _ in 1:3]
julia> a[1]["example"] = 1.                                                                                           
1.0
julia> println(a)
[Dict("example" => 1.0), Dict("example" => 0.0), Dict("example" => 0.0)]                                                                                                       

Alternative map solution

If you really dislike list comprehensions you could use map to achieve the same solution by instantiating multiple instances of the same looking dictionary.

julia> b = map(x -> Dict("example" => 0.), 1:3)
3-element Vector{Dict{String, Float64}}:
 Dict("example" => 0.0)
 Dict("example" => 0.0)
 Dict("example" => 0.0)

julia> b[1]["example"] = 2.0
2.0

julia> println(b)
[Dict("example" => 2.0), Dict("example" => 0.0), Dict("example" => 0.0)]

Upvotes: 5

Related Questions