Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to tuple in julia

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

like image 535
ilovecp3 Avatar asked Dec 08 '22 22:12

ilovecp3


2 Answers

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}()
like image 166
Andy Hayden Avatar answered Dec 26 '22 03:12

Andy Hayden


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 ....

like image 33
amrods Avatar answered Dec 26 '22 02:12

amrods