Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary from two Arrays/Vectors in Julia

Tags:

julia

How can I create a Dict() from two arrays, one with the keys and one with the values:

a = ["a", "b", "c"] # keys
b = [1,2,3]         # values
like image 387
Georgery Avatar asked Oct 14 '20 12:10

Georgery


2 Answers

Solution 1

Dict(zip(a,b))

Solution 2

Dict(a .=> b)
like image 106
Georgery Avatar answered Sep 30 '22 16:09

Georgery


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
like image 34
Antonello Avatar answered Sep 30 '22 16:09

Antonello