Convert value type of dictionary

Hello!

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

map(v->parse(Float64,v),values(mydict))

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(Iterators.map(f, 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.

3 Likes

I am new to Julia and I am not sure what version you need to use my suggested solution.

‘’’
myphonebook = Dict(“Jenny” => “8675309”, “Ghostbusters” => “5552368”)
myphonebook = Dict(keys(myphonebook) .=> parse.(Float64, values(myphonebook)))

Results:
Dict{String, Float64} with 2 entries:
“Jenny” => 8.67531e6
“Ghostbusters” => 5.55237e6
‘’’
As @rocco_sprmnt21 noted my answer was incomplete. I think I have corrected it.

1 Like
Dict((=>).(first(zip(d...)),parse.(Float64,last(zip(d...)))))
1 Like

A little cleaner (oops, I see the marked answer gives this too):

julia> myphonebook = Dict("Jenny" => "8675309",
  "Ghostbusters" => "5552368");

julia> Dict(k=>parse(Float64,v) for (k,v) in myphonebook)
Dict{String, Float64} with 2 entries:
  "Jenny"        => 8.67531e6
  "Ghostbusters" => 5.55237e6