Conversion of an array of tuples into a dictionary

Sorry for this easy question but I’m lost.
I want to convert this array of tuples:

ls = [(['A' 'B'], 1)

        (['Z'], 2)]

into this dictionary
Dict('A' => 1, 'B' => 1, 'Z' => 2)
I tried this
d1 = [ls[i][1] .=> ls[i][2] for i in 1:length(ls)]
and this
d2 = [map(x -> x => ls[i][2], collect(ls[i][1])) for i in 1:length(ls)]
both without success.

Dictionaries are pairs of keys and values. So, in order to produce Dict('A' => 1, 'B' => 1, 'Z' => 2) you need to have an array of tuple that represents that – meaning a value for every key.

julia> ls = [("A",1), ("B",1), ("Z",2)]
3-element Vector{Tuple{String, Int64}}:
 ("A", 1)
 ("B", 1)
 ("Z", 2)

julia> Dict(ls)
Dict{String, Int64} with 3 entries:
  "Z" => 2
  "B" => 1
  "A" => 1

separating (["A","B"], 1) into ("A",1) and ("B",1) in your array should do the job.

1 Like

Just write a nested loop:

d = Dict{Char,Int}()
for (keys, val) in ls, key in keys
    d[key] = val
end

Higher-order facilities like map and broadcasting are great, and are often very convenient, but sometimes an explicit loop is the clearest way to do something. (And loops are fast in Julia; for people coming from languages like Python or Matlab, one has to unlearn the instinct to avoid explicit loops at all costs.)

PS. Note that ['A' 'B'] in Julia is a 1×2 matrix of Char. This works fine with my loops here, but you probably wanted a 1d array, which is denoted ['A', 'B'] (i.e., with a comma).

3 Likes

Fantastic!

just realized @sbacelar really meant the exact array of tuples :grimacing: so sorryy :slightly_frowning_face: