If I have two vectors:
mykeys = ["a", "b", "c"]
myvals = [420, 69, 1337]
How can I make them into a Dict of corresponding pairs like:
Dict("a" => 420, "b" => 69, "c" => 1337)
Perfect use case for broadcasting:
julia> Dict(mykeys .=> myvals)
Dict{String, Int64} with 3 entries:
"c" => 1337
"b" => 69
"a" => 420
There's also a Dict comprehension similar to e.g. Python:
julia> Dict((k, v) for (k, v) ∈ zip(mykeys, myvals))
Dict{String, Int64} with 3 entries:
"c" => 1337
"b" => 69
"a" => 420
and as a general hint usually when you do ?SomeType
you get a help entry which includes contructors:
help?> Dict
search: Dict IdDict WeakKeyDict AbstractDict redirect_stdin redirect_stdout redirect_stderr isdispatchtuple to_indices parentindices LinearIndices CartesianIndices deuteranopic optimize_datetime_ticks DimensionMismatch
Dict([itr])
Dict{K,V}() constructs a hash table with keys of type K and values of type V. Keys are compared with isequal and hashed with hash.
Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> Dict([("A", 1), ("B", 2)])
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
Alternatively, a sequence of pair arguments may be passed.
julia> Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
Another trick is to just type your constructor with an opening bracket and hit \tab \tab
to get the REPL to show you methods you can call:
julia> Dict(
Dict() in Base at dict.jl:118 Dict(ps::Pair{K, V}...) where {K, V} in Base at dict.jl:124 Dict(kv) in Base at dict.jl:127
Dict(kv::Tuple{}) in Base at dict.jl:119 Dict(ps::Pair...) in Base at dict.jl:125
Now as per your comment, I agree that it might not be immediately obvious why .=>
works: what happens is that it creates a vector of Pair
s:
julia> mykeys .=> myvals
3-element Vector{Pair{String, Int64}}:
"a" => 420
"b" => 69
"c" => 1337
Which constructor method for Dict()
does this call you ask?
julia> x = mykeys .=> myvals;
julia> @which Dict(x)
Dict(kv) in Base at dict.jl:127
(@which
is one of the nicest things in Julia to figure out what's happening)
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