Adding elements to dictionaries?

Suppose I have a dictionary d = Dict("a"=->(1,2,3)) and I want to add an element with key "b" to the dictionary. The following works:

merge!(d,Dict("b"=>(4,5,6)))

However, this only seems to work if the value of the key has the same “type”. In other words, the following fails:

merge!(d, Dict("b"=>(7,9)))

because the value tuple has 2 elements instead of 3.

On the other hand, creating both elements at the same time works:

d = Dict("a"=>(1,2,3), "b"=>(7,9))

Question: is there/what is a more flexible method to add elements to a dictionary than the merge! method?

1 Like

You have to construct the original dictionary d with this flexibility in mind, for example

d = Dict{String,Any}("a"=->(1,2,3))

would allow values of type String as dictionary keys and Anything as dictionary values.

2 Likes

creates a specific dictionary where keys are String and values are exactly Tuple{Int64,Int64,Int64}}, thats why you get an error if you try to add a value which is Tuple{Int64,Int64}}.

The line

gives you the hint on how you could do it:

julia> d = Dict("a"=>(1,2,3), "b"=>(7,9))
Dict{String,Tuple{Int64,Int64,Vararg{Int64,N} where N}} with 2 entries:
  "b" => (7, 9)
  "a" => (1, 2, 3)

See the type definition printed out. With that you can define the Dict like:

d=Dict{String,Tuple{Int64,Vararg{Int64,N} where N}}()

Which accepts any tuple:

julia> d["a"]=(1,2,3)
(1, 2, 3)

julia> d["b"]=(7,9)
(7, 9)

This is the way to assign new key,value pairs, no need for merge!.
Or (as ninja’d above :slight_smile: ) use Any.

But use the correct syntax: not =-> , but =>

4 Likes