andrdpedro
andrdpedro

Reputation: 171

Sort values of lists of a Dicts

I have a Dicitionary where the values are lists. I want to sort these lists inside the Dict.

Dict("Income" => ["Top 10%", "Lower 50%", "31 - 40%", "21 - 30%", "41 - 50%", "Undetermined", "11 - 20%"], 
"Age" => ["65+", "55-64", "45-54", "Unknown", "18-24", "25-34", "35-44"], 
"Gender" => ["Undetermined", "Female", "Male"], 
"Device" => ["Desktop", "Mobile", "Tablet"])

Sorted will be:

Dict("Income" => ["11 - 20%", "21 - 30%", "31 - 40%", "41 - 50%", "Lower 50%", "Top 10%", "Undetermined"], 
"Age" => ["18-24", "25-34", "35-44", "45-54", "55-64", "65+", "Unknown"], 
"Gender" => ["Female", "Male", "Undetermined"], 
"Device" => ["Desktop", "Mobile", "Tablet"])

Upvotes: 5

Views: 89

Answers (1)

Antonello
Antonello

Reputation: 6431

julia> mydict = Dict(  "Income" => ["Top 10%", "Lower 50%", "31 - 40%", "21 - 30%", "41 - 50%", "Undetermined", "11 - 20%"], 
                       "Age" => ["65+", "55-64", "45-54", "Unknown", "18-24", "25-34", "35-44"], 
                       "Gender" => ["Undetermined", "Female", "Male"], 
                       "Device" => ["Desktop", "Mobile", "Tablet"]);

julia> sort!.(values(mydict))
4-element Vector{Vector{String}}:
 ["11 - 20%", "21 - 30%", "31 - 40%", "41 - 50%", "Lower 50%", "Top 10%", "Undetermined"]
 ["18-24", "25-34", "35-44", "45-54", "55-64", "65+", "Unknown"]
 ["Female", "Male", "Undetermined"]
 ["Desktop", "Mobile", "Tablet"]

julia> mydict
Dict{String, Vector{String}} with 4 entries:
  "Income" => ["11 - 20%", "21 - 30%", "31 - 40%", "41 - 50%", "Lower 50%", "Top 10%", "Undetermined"]
  "Age"    => ["18-24", "25-34", "35-44", "45-54", "55-64", "65+", "Unknown"]
  "Gender" => ["Female", "Male", "Undetermined"]
  "Device" => ["Desktop", "Mobile", "Tablet"]

Of course, you have textual elements, so the actual sorting will be based on alphanumerical characteristics.

Upvotes: 6

Related Questions