How do I sort a dictionary by value in Julia?

Viewed 1067

I have two arrays:

a = [11,22,33,44,55]
b = [66,77,88,99,100]

which I used to create a dictionary by doing:

combined_dict = Dict(zip(a, b))

How can I sort the Dictionary by value?

3 Answers

The builtin dictionary type (Dict) is unordered so it is not clear what you are asking for -- it can't be sorted. If you want an ordered dictionary you can use an OrderedDict from the OrderedCollections package:

julia> a = [11,22,33,44,55];

julia> b = [100,99,88,77,66];

julia> combined_dict = OrderedDict(zip(a, b))
OrderedDict{Int64,Int64} with 5 entries:
  11 => 100
  22 => 99
  33 => 88
  44 => 77
  55 => 66

In order to sort by value you can use the byvalue=true as a keyword argument to sort (byvalue=false is the default, i.e. sort by keys):

julia> sort(combined_dict; byvalue=true)
OrderedDict{Int64,Int64} with 5 entries:
  55 => 66
  44 => 77
  33 => 88
  22 => 99
  11 => 100

In order to sort the dictionary value it is not needed to use the OrderedDict.
Using the sort function would suffice for your use case.

julia> a = [11,22,33,44,55];

julia> b = [100,99,88,77,66];

julia> combined_dict = Dict{Int, Int}(zip(a, b))
Dict{Int64, Int64} with 5 entries:
  22 => 99
  55 => 66
  33 => 88
  11 => 100
  44 => 77

julia> sort(combined_dict, byvalue=true)
OrderedDict{Int64, Int64} with 5 entries:
  55 => 66
  44 => 77
  33 => 88
  22 => 99
  11 => 100

Tested on Julia 1.6

Related