Julia: Sorting a dict of types

谁都会走 提交于 2020-08-10 04:39:15

问题


I have a dict filled with Job types

A job has a name(string) and a score(int)

I managed to load the jobs into a Dict, and I want to sort them using the Sort method based on the jobs scores. However, when I sort the dict (call it jobs), it gives me a new vector of the sorted scores.

is there any way to sort the dict while preserving which job has its specific score?

jobs = Dict([(nurse, nurse.score), (construction, construction.score),
           (programmer, programmer.score), (retail, retail.score)])

sort(collect(values(jobs)))

so if I have nurse with a score of 3, programmer with a score of 6, retail with a score of 0, and construction with a score of 4, I would want the output to be a dict (or something similar) that would contain:

  1. programmer, 6
  2. construction, 4
  3. nurse, 3
  4. retail, 0

or, even better, could I sort it by the values but get the output as a vector with just the jobs? then reference that vector later in my code?


回答1:


this works in your specific case:

jobs = Dict("nurse"=>3, "construction"=>4, "programmer"=>6, "retail"=>0)
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sort(collect(values(jobs)), rev=true)

julia> sortedNames = [jobpairs[i] for i in indexin(sind, jobvalues)]
4-element Array{Any,1}:
 "programmer"=>6  
 "construction"=>4
 "nurse"=>3       
 "retail"=>0    

if two keywords have the same value, we need do more work to deal with indices.

UPDATE:

as Matt suggested in the comment below, we should use sortperm rather than indexin which won't work if the dict has at least two keywords that have the same value.

jobs = Dict("nurse"=>3, "construction"=>4, "foo"=>3, "programmer"=>6, "retail"=>0) 
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sortperm(collect(values(jobs)), rev=true)

julia> sortedNames = [jobpairs[i].first for i in sind]
5-element Array{Any,1}:
 "programmer"  
 "construction"
 "foo"        
 "nurse"       
 "retail"     



回答2:


Sorting algorithm with less code, but I don't know about the performance and you would not have a dict as result:

sort(collect(jobs),by=x->x[2],rev=true)



回答3:


Currently I think the recommended way to do it is:

julia> using DataStructures

julia> jobs = Dict("nurse"=>3, "construction"=>4, "programmer"=>6, "retail"=>0)
Dict{String,Int64} with 4 entries:
  "programmer"   => 6
  "retail"       => 0
  "construction" => 4
  "nurse"        => 3

julia> sort!(OrderedDict(jobs), byvalue=true, rev=true)
OrderedDict{String,Int64} with 4 entries:
  "programmer"   => 6
  "construction" => 4
  "nurse"        => 3
  "retail"       => 0

In this way you get a dictionary as you wanted, but it is OrderedDict so it can be sorted as you see.



来源:https://stackoverflow.com/questions/33879158/julia-sorting-a-dict-of-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!