How to append to arrays in a dictionary one by one?

question
array
dictionary
loops

#1

Hello,
I would like to append to arrays in a dict different items for each entry. What I coded simplified is:

entries = [“A”,“B”,“C”]
entryvalues = fill(Float64[],size(entries))
dict = Dict(zip(entries, entryvalues))

which gives so far:

Dict{String,Array{Float64,1}} with 3 entries:
“B” => Float64[]
“A” => Float64[]
“C” => Float64[]

Until here it’s fine. Then I would like to append different values to the different entryvalues. I tried:

i=1
for x in dict
append!(x[2],5*i)
println(x[1],x[2])
i=i+1
end

the output is:

B[5.0]
A[5.0, 10.0]
C[5.0, 10.0, 15.0]

and the whole dict now looks like
“B” => [5.0, 10.0, 15.0]
“A” => [5.0, 10.0, 15.0]
“C” => [5.0, 10.0, 15.0]

what I was expecting for the final dict is something like
“B” => [5.0]
“A” => [10.0]
“C” => [15.0]

so instead of only appending to the entryvalue of only “A”, only “B” or only “C” in the loop, it appends the value to all three entries. That appeared weird to me and I don’t know, how to fix this. Is there another way to code it or is it a bug in juliaLang?

Thank you,
Wei


#2

This fills a vector with the same empty vector of Float64. If you want them all to be separate you can change this to

entryvalues = [Float64[] for _ in 1:length(entries)]

See also PSA: how to quote code with backticks for formatting your code.


#3

Nice, that solves the problem!
Thank you.