Is it possible to sort a dictionary in Julia?
The byvalue
keyword for the sort
function (or sort!
for mutating/in place sorting) is useful for sorting dictionaries in order of their values (as opposed to their keys). The result will be of type OrderedDict from OrderedCollections.jl (it's also re-exported by DataStructures.jl).
list1 = [2,1,3,4,5]
list2 = [9,10,8,7,6]
dictionary1 = Dict(zip(list1,list2))
Sort by value (i.e. by list2):
sort(dictionary1; byvalue=true)
Output:
OrderedDict{Int64, Int64} with 5 entries:
5 => 6
4 => 7
3 => 8
2 => 9
1 => 10
Sort by key (i.e. by list1):
sort(dictionary1)
Output:
OrderedDict{Int64, Int64} with 5 entries:
1 => 10
2 => 9
3 => 8
4 => 7
5 => 6
Sort also takes a by
keyword, which means you can do:
julia> sort(collect(dictionary1), by=x->x[2])
5-element Array{Tuple{Int64,Int64},1}:
(1,6)
(2,7)
(3,8)
(4,9)
(5,19)
Also note that there is a SortedDict
in DataStructures.jl, which maintains sort order, and there's an OrderedDict
which maintains insertion order. Finally, there's a pull request which would allow direct sorting of OrderedDicts
(but I need to finish it up and commit it).
While SortedDict
may be useful if it is necessary to keep the dictionary sorted, it is often only necessary to sort the dictionary for output, in which case, the following may be what is required:
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,19]
dictionary1 = Dict(zip(list1,list2))
sort(collect(dictionary1))
... which produces:
5-element Array{(Int64,Int64),1}:
(1,6)
(2,7)
(3,8)
(4,9)
(5,19)
We can sort by values with:
sort(collect(zip(values(dictionary1),keys(dictionary1))))
... which gives:
5-element Array{(Int64,Int64),1}:
(6,1)
(7,2)
(8,3)
(9,4)
(19,5)