I have a question related to dictionary initialization. The code snippet illustrates the problem:
function DictGen(KeyList, InitVal)
return Dict(i => InitVal for i in collect(Iterators.product(KeyList...)))
end
# make some key indices
N = ["N"*string(n) for n = 1:3]
T = ["T"*string(t) for t = 1:5]
# manual dictionary generation
D1 = Dict(i => Array{String}(undef,0) for i in collect(Iterators.product([N,T]...)))
push!(D1["N1","T1"], "one")
# equivalent dictionary generation wih function
D2 = DictGen([N,T], Array{String}(undef,0))
push!(D2["N1","T1"], "one")
The goal in this code is to produce a dictionary with keys generated from an Array of strings, and set an empty array as a default value. Subsequently, I want to push!() values to the dictionary to build up lists.
It works as intended if executed manually, but not if wrapped in a function. Here are D1 and D2 on execution of the script:
julia> D1
Dict{Tuple{String, String}, Vector{String}} with 15 entries:
("N1", "T5") => []
("N1", "T3") => []
("N3", "T5") => []
("N2", "T2") => []
("N2", "T3") => []
("N1", "T1") => ["one"]
("N1", "T2") => []
("N2", "T5") => []
("N3", "T3") => []
("N3", "T4") => []
⋮ => ⋮
julia> D2
Dict{Tuple{String, String}, Vector{String}} with 15 entries:
("N1", "T5") => ["one"]
("N1", "T3") => ["one"]
("N3", "T5") => ["one"]
("N2", "T2") => ["one"]
("N2", "T3") => ["one"]
("N1", "T1") => ["one"]
("N1", "T2") => ["one"]
("N2", "T5") => ["one"]
("N3", "T3") => ["one"]
("N3", "T4") => ["one"]
⋮ => ⋮
D1 is the anticipated behavior, D2 seems like it ought to be equivalent, but apparently it is not. Can someone explain how these work, and provide the working function equivalent?