Sort values of lists of a Dicts
Asked Answered
O

1

5

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"])
Octavie answered 29/11, 2022 at 14:11 Comment(0)
W
6
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.

Weighting answered 29/11, 2022 at 14:21 Comment(1)
or foreach(sort!, values(mydict)) to make a bit less allocations.Fisherman

© 2022 - 2024 — McMap. All rights reserved.