Create a Dictionary from Arrays of Keys and Values

I am trying create a Dictionary from Arrays of Keys and Values

julia> id = [1,2,3,4];
julia> coord = [0 0 0;1 0 0;5 3 0;6 5 1];

and I want something like:

Dict(id,coord)

i.e.

julia> X = Dict(1 => [0,0,0],
                2 => [1,0,0],
                3 => [5,3,0],
                4 => [6,5,1])
Dict{Int64,Array{Int64,1}} with 4 entries:
  4 => [6, 5, 1]
  2 => [1, 0, 0]
  3 => [5, 3, 0]
  1 => [0, 0, 0]
2 Likes

One way is Dict(zip(keys, values)).

3 Likes

Or the slick new syntax Dict(ks .=> vs) which simply falls out of broadcasting and the Dict constructor.

29 Likes

It would be cool if the documentation had a “cool tricks that are hard to look up in the documentation” documentation page.

14 Likes

Thank you so much for your help.
I don’t get an array in the values (julia v0.7)

julia> Dict(id .=> coord)
Dict{Int64,Int64} with 4 entries:
  4 => 1
  2 => 0
  3 => 0
  1 => 0

i.e.

Dict{Int64,Array{Int64,1}} with 4 entries:
  4 => [6, 5, 1]
  2 => [1, 0, 0]
  3 => [5, 3, 0]
  1 => [0, 0, 0]

You need:

julia> Dict( id .=> [coord[i,:] for i=1:4] )
Dict{Int64,Array{Int64,1}} with 4 entries:
  4 => [6, 5, 1]
  2 => [1, 0, 0]
  3 => [5, 3, 0]
  1 => [0, 0, 0]

Also, this is faster:

julia> Dict( (id[i] => coord[i,:] for i=1:4) )
Dict{Int64,Array{Int64,1}} with 4 entries:
  4 => [6, 5, 1]
  2 => [1, 0, 0]
  3 => [5, 3, 0]
  1 => [0, 0, 0]

Edit: I left two extra unnecessary parens, thanks to @StefanKarpinski, this can be much nicer:

Dict( id[i] => coord[i,:] for i=1:4 )
4 Likes

You can drop one pair of parens in the latter one.

1 Like

Yes, this makes it much nicer, thank you.