Dictionary from two Arrays/Vectors in Julia

To complement the Georgery's answer, note that the first method (Dict(zip(a,b))) is much faster for small vectors, but the difference becomes negligible for larger ones:

julia> using BenchmarkTools

julia> a = rand(5); b = rand(5);

julia> @benchmark Dict(zip(a,b))
BenchmarkTools.Trial: 
  memory estimate:  672 bytes
  allocs estimate:  6
  --------------
  minimum time:     344.143 ns (0.00% GC)
  median time:      356.382 ns (0.00% GC)
  mean time:        383.371 ns (6.12% GC)
  maximum time:     8.124 μs (94.84% GC)
  --------------
  samples:          10000
  evals/sample:     217

julia> @benchmark Dict(a .=> b)
BenchmarkTools.Trial: 
  memory estimate:  832 bytes
  allocs estimate:  7
  --------------
  minimum time:     950.615 ns (0.00% GC)
  median time:      1.013 μs (0.00% GC)
  mean time:        1.051 μs (2.30% GC)
  maximum time:     62.573 μs (97.09% GC)
  --------------
  samples:          10000
  evals/sample:     26

julia> a = rand(50000);b = rand(50000);

julia> @benchmark Dict(zip(a,b))
BenchmarkTools.Trial: 
  memory estimate:  5.67 MiB
  allocs estimate:  38
  --------------
  minimum time:     1.581 ms (0.00% GC)
  median time:      1.611 ms (0.00% GC)
  mean time:        1.675 ms (3.41% GC)
  maximum time:     2.917 ms (25.30% GC)
  --------------
  samples:          2984
  evals/sample:     1

julia> @benchmark Dict(a .=> b)
BenchmarkTools.Trial: 
  memory estimate:  6.43 MiB
  allocs estimate:  40
  --------------
  minimum time:     1.624 ms (0.00% GC)
  median time:      1.666 ms (0.00% GC)
  mean time:        1.740 ms (3.79% GC)
  maximum time:     3.762 ms (14.17% GC)
  --------------
  samples:          2873
  evals/sample:     1

Solution 1

Dict(zip(a,b))

Solution 2

Dict(a .=> b)

Tags:

Julia