Convert value type of dictionary


How would I convert Dict{String,String} to Dict{String,Float}? I have got this far so that I can convert the values:


But how can I match these with the original keys and put them back into the dictionary? keys(mydict) are the keys but they are not necessarily in the same order as values?

julia> f((k,v)) = k => parse(Float64, v)
f (generic function with 1 method)      
julia> Dict(, pairs(d)))
Dict{String, Float64} with 1 entry:    
  "a" => 1.0                           

# slower than the above for repeated use on the REPL, but if you like Generators
julia> Dict(k => parse(Float64, v) for (k,v) in pairs(d)) 
Dict{String, Float64} with 1 entry:                      
  "a" => 1.0                                             

keys(mydict) returns a KeySet, which is unordered because the Dict in Base is an unordered dict. If you require an ordered dict, check out DataStructures.jl, but in the majority of use cases you won’t need an ordered one.

1 Like