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??
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 String
s and vals is a Vector of Int
s.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With