Newbie in julia, got quite confused.
Here is an array:
array=["a","b",1]
I define a dictionary
dict=Dict()
dict["a","b"]=1
I want to use 'array' to define the dict
dict2 = Dict()
dict2[array[1:2]]=1
but they are not the same,
julia> dict
Dict{Any,Any} with 1 entry:
("a","b") => 1
julia> dict2
Dict{Any,Any} with 1 entry:
Any["a","b"] => 1
How can I use 'array' to generate 'dict' instead of 'dict2'? Thanks
You can use the splat operator when doing assignment:
julia> dict = Dict()
Dict{Any,Any} with 0 entries
julia> dict[array[1:2]...] = 1
1
julia> dict
Dict{Any,Any} with 1 entry:
("a","b") => 1
Note: You can specify the types in your Dict, that way these types of errors are protected against:
dict = Dict{Tuple{String, String}, Int}()
Julia interprets something like dict["a", "b"] = 1
as dict[("a", "b")] = 1
, that is a multidimensional key is interpreted as a tuple key.
The issue arises because the output of array[1:2]
is not a tuple but an array. You can convert an array to a tuple with
tup = tuple(array[1:2]...)
Then you can
dict2 = Dict()
dict2[tup] = 1
Notice the use of the splat operator ...
that unpacks array[1:2]
to create a 2-element tuple instead of the 1-element tuple (with its only element being a 2-element array) that is created when you don't use ...
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With