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?
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?
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
To sort the tuples by lexicographic order, you can simply do:
julia> sort(collect(zip(values(combined_dict), keys(combined_dict))))
5-element Array{Tuple{Int64,Int64},1}:
(66, 11)
(77, 22)
(88, 33)
(99, 44)
(100, 55)
See this post for reference: Is it possible to sort a dictionary in Julia?
Learn more about the sort function here.
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