Home > Net >  Add a Key-Value Pairs to an existing key in dictionary in Julia Language
Add a Key-Value Pairs to an existing key in dictionary in Julia Language

Time:11-04

i am using Julia 1.63 and i am currently trying to create a dictionary in a loop. I can start with the following dictionary.

dict = Dict("A_1" => 1, "B_1" => 2, "X" => "A_1" => 1)
Dict{String, Any} with 3 entries:
  "X"   => "A_1"=>1
  "B_1" => 2
  "A_1" => 1

Now i want to add to the "X" key the key-value pair "B_2" => 2

I tried the following:

push!(dict["X"],Dict("B_2" => 2))
ERROR: MethodError: no method matching push!(::Pair{String, Int64}, ::Dict{String, Int64})
Closest candidates are:
  push!(::Any, ::Any, ::Any) at abstractarray.jl:2387
  push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388
  push!(::AbstractChannel, ::Any) at channels.jl:10

push!(dict["X"],"B_2" => 2)
ERROR: MethodError: no method matching push!(::Pair{String, Int64}, ::Pair{String, Int64})
Closest candidates are:
  push!(::Any, ::Any, ::Any) at abstractarray.jl:2387
  push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388
  push!(::AbstractChannel, ::Any) at channels.jl:10

The one thing that is puzzling for me that this works on an upper level in the dict.

push!(dict,"B_2" => 2)
Dict{String, Any} with 4 entries:
  "B_2" => 2
  "X"   => "A_1"=>1
  "B_1" => 2
  "A_1" => 1

Is there something obvious i am missing? Thanks for your help.

CodePudding user response:

The problem is that the value of "X" is not a Dict, it's a Pair. If you want to assign multiple Pairs to one key you should use Dict instead. You have to initialize it accordingly.

julia> dict = Dict("A_1" => 1, "B_1" => 2, "X" => Dict("A_1" => 1))
Dict{String, Any} with 3 entries:
  "X"   => Dict("A_1"=>1)
  "B_1" => 2
  "A_1" => 1
julia> push!(dict["X"],"B_2" => 2) 
Dict{String, Int64} with 2 entries:
  "B_2" => 2
  "A_1" => 1
julia> dict
Dict{String, Any} with 3 entries:
  "X"   => Dict("B_2"=>2, "A_1"=>1)
  "B_1" => 2
  "A_1" => 1
  • Related