从键和值数组创建一个字典

Job*_*Job 6 julia

我有:

keys = ["a", "b", "j"]
vals = [1, 42, 9]
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

somedic = ["a"=>1, "b"=>42, "j"=>9]
Run Code Online (Sandbox Code Playgroud)

Dict{String,Int64} with 3 entries:
"j" => 9
"b" => 42
"a" => 1
Run Code Online (Sandbox Code Playgroud)

但是怎么样?

Job*_*Job 15

像这样:

keys = ["a", "b", "j"]
vals = [1, 42, 9]
yourdic = Dict(zip(keys, vals))
Run Code Online (Sandbox Code Playgroud)

返回的Dict将是类型Dict{String, Int}(即Dict{String, Int64}在我的系统上),因为键是Strings 的向量,而val是向量的Ints.

如果你想在快译通有那么具体类型,例如AbstractStringReal,你可以这样做:

Dict{AbstractString, Real}(zip(keys, vals))
Run Code Online (Sandbox Code Playgroud)

如果您在一个数组中有对:

dpairs = ["a", 1, "b", 42, "j", 9]
Run Code Online (Sandbox Code Playgroud)

你可以做:

Dict(dpairs[i]=>dpairs[i+1] for i in 1:2:length(dpairs))
Run Code Online (Sandbox Code Playgroud)

与上面相同的语法适用于获得较少的特定类型,例如:

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