Dictionary values ascending or descending

Hi,

I have a dictionary of characters and their frequency in a text(or word):

  'H' => 1
  'l' => 2
  'e' => 1
  'o' => 1

and I want to order it by value so:

  'H' => 1
  'e' => 1
  'o' => 1
  'l' => 2

the order of ‘H’, ‘e’ or ‘o’ is irrelevant. It simply needs to be ordered either by ascending or descending value order. Is there a built in function for that?

julia> d = Dict('H' => 1, 'l' => 2, 'e' => 1,'o' => 1)
julia> sort(collect(keys(d)); lt=(a,b)->d[a]<d[b])
4-element Vector{Char}:
 'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase)
 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
 'o': ASCII/Unicode U+006F (category Ll: Letter, lowercase)
 'l': ASCII/Unicode U+006C (category Ll: Letter, lowercase)
1 Like

my previous reply was not correct, I have edited it but someone pressed the like, hence this one

My use of Revise was interfering

You can use the by keyword (and also the rev keyword if you need descending order):

julia> sort(collect(d), by = x -> x.second)
4-element Vector{Pair{Char, Int64}}:
 'H' => 1
 'e' => 1
 'o' => 1
 'l' => 2

julia> sort(collect(d), by = x -> x.second, rev = true)
4-element Vector{Pair{Char, Int64}}:
 'l' => 2
 'H' => 1
 'e' => 1
 'o' => 1
3 Likes

Or sort!(collect(d), by=last), which avoids allocating a second array and utilizes last for conciseness.

4 Likes