Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Dictionary from Arrays of Keys and Values

Tags:

julia

I have:

keys = ["a", "b", "j"]
vals = [1, 42, 9]

and I want something like:

somedic = ["a"=>1, "b"=>42, "j"=>9]

i.e.

Dict{String,Int64} with 3 entries:
"j" => 9
"b" => 42
"a" => 1

But how??

like image 562
JobJob Avatar asked Sep 17 '14 17:09

JobJob


1 Answers

Keys & Values to Dict

ks = ["a", "b", "j"]  # keys
vals = [1, 42, 9]     # values
thedict = Dict(zip(ks, vs))
# or using broadcast syntax, which looks quite nice IMO (though 
# does create a temporary Vector of key=>value pairs)
thedict = Dict(ks .=> 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.


Specifying the Types

If you want to specify the types of the Dict's keys or values, e.g. AbstractString and Real, you can do:

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

Related aside: Pairs in a single Vector/Array

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 specify the respective types of the keys and values, e.g.:

Dict{Any, Number}(dpairs[i]=>dpairs[i+1] for i in 1:2:length(dpairs))
like image 135
JobJob Avatar answered Sep 28 '22 12:09

JobJob