Creating a dictionary from arrays of keys and values

I have:

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

and i need something like:

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

i.e.

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

But how?

+6
source share
2 answers

Same:

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

The returned Dict will be of type Dict{String, Int} (that is, Dict{String, Int64} on my system), since the keys are Vector of String and vals is the vector Int s.

If you want Dict to have less specific types, for example. AbstractString and Real , you can do:

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

If you have pairs in one 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 is used to get less specific types, for example:

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

I don't know Julia, but if Julia has a zip , then this should work: dict(zip(keys,vals)) .

(confession: this can be done in python).

0
source

Source: https://habr.com/ru/post/975440/


All Articles