Array to tuple in julia
Asked Answered
O

3

5

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

Odlo answered 27/5, 2016 at 18:16 Comment(0)
A
7

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}()
Ansilme answered 27/5, 2016 at 20:4 Comment(0)
M
6

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

Massarelli answered 27/5, 2016 at 18:50 Comment(0)
F
1

In Julia 1.6 the following code works:

array=["a","b",1]
tup = Tuple(array[1:2])
dict2 = Dict()
dict2[tup] = 1

julia> dict2
Dict{Any, Any} with 1 entry:
  ("a", "b") => 1

It is no longer necessary to go via the splat operator

Fe answered 21/6, 2021 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.