Create a Dictionary from Arrays of Keys and Values

Like so:

keys = ["a", "b", "j"]
vals = [1, 42, 9]
yourdic = Dict(zip(keys, vals))

The returned Dict will be of type Dict{String, Int} (i.e. Dict{String, Int64} on my system), since keys is a Vector of Strings and vals is a Vector of Ints.

If you want the Dict to have less specific types, e.g. AbstractString and Real, you can do:

Dict{AbstractString, Real}(zip(keys, vals))

If you have pairs in a single array:

dpairs = ["a", 1, "b", 42, "j", 9]

you can do:

Dict(dpairs[i]=>dpairs[i+1] for i in 1:2:length(dpairs))

the same syntax as above applies to get less specific types, e.g.:

Dict{Any, Number}(dpairs[i]=>dpairs[i+1] for i in 1:2:length(dpairs))

Tags:

Julia