Reputation: 33
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
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
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)]
map
solutionIf 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