How to append a value to a nested dictionary?

Viewed 223

I'm trying to create a list nested within a dictionary and append values to it. In python, I would have written the following:

samples = {'x' : [1], 'y' : [-1]}

and to append values in a for-loop:

samples['x'].append(new_value)

How can I achieve something equivalent in Julia?

1 Answers

Here it is:

julia> samples = Dict("x" => [1], "y" => [-1])
Dict{String, Vector{Int64}} with 2 entries:
  "x" => [1]
  "y" => [-1]

julia> push!(samples["x"],4);

julia> samples
Dict{String, Vector{Int64}} with 2 entries:
  "x" => [1, 4]
  "y" => [-1]

Perhaps in Julia one would consider Symbols as keys instead of Strings so it could be samples = Dict(:x => [1], :y => [-1])

Finally, if you know that the keys are only x and y you would use a NamedTuple:

julia> samples2 = (x = [1], y = [-1])
(x = [1], y = [-1])

julia> typeof(samples2)
NamedTuple{(:x, :y), Tuple{Vector{Int64}, Vector{Int64}}}

julia> push!(samples2.x, 111);

julia> samples2
(x = [1, 111], y = [-1])
Related