Change dictionary values in array

Person = fill(Dict(“x” => 0,“status” => 0,“color” => “black”),5)
Person[1][“color”] = “green”
HI
I have an array of dictionaries. when I change the value of single dictionary, all other values in other dictionaries are affected.
How to prevent this in Julia?

fill will place the same object into the resulting array, so that you change all instances when changing one. This behaviour is discussed in the docstring:

help?> fill
  fill(x, dims::Tuple)
  fill(x, dims...)

  Create an array filled with the value x. For example, fill(1.0, (5,5)) returns a 5×5 array of floats, with each element initialized to 1.0.

(...)

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

  julia> A = fill(zeros(2), 2);
  
  julia> A[1][1] = 42; # modifies both A[1][1] and A[2][1]
  
  julia> A
  2-element Vector{Vector{Float64}}:
   [42.0, 0.0]
   [42.0, 0.0]

You can use a comprehension instead:

julia> person = [Dict("x" => 0, "status" => 0, "color" => "black") for _ ∈ 1:5]
5-element Vector{Dict{String, Any}}:
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")

julia> person[1]["color"] = "green"
"green"

julia> person
5-element Vector{Dict{String, Any}}:
 Dict("status" => 0, "x" => 0, "color" => "green")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
 Dict("status" => 0, "x" => 0, "color" => "black")
1 Like

Worked perfectly, Many thanks

1 Like