How do I sort a dictionary by its keys?

I want to sort this by its keys:

5-element Dictionaries.HashDictionary{Int64,Any}
 4 │ 0.2199244
 2 │ 0.2000908
 3 │ 0.19014
 5 │ 0.2099752
 1 │ 0.1798696

How did you construct the dictionary? Maybe include code to make it.

For normal Dictionaries

dict = Dict(i => rand() for i in 1:5)
sort(collect(dict), by = x->x[1])
q = 0.2
c = 1.1
p = [0.18, 0.2, 0.19, 0.22, 0.21]
@assert sum(p) == 1

function Y()
    return ceil(Int, rand()*5)
end
# Y()
function X()
    while true
        y = Y()
        if rand() <= (p[y]/(q*c)) # if we use q*c without parens the instability breaks our results.
            return y
        end
    end
end
# X()

n = 10^7
@time a = [X() for i in 1:n]

using SplitApplyCombine
dict = map(x -> length(x)/n, group(a))

Note that Dictionaries.HashDictionary has no order defined (similar to Dict), so the question does not make sense.

You can collect key-value pairs in a vector and sort them though, as @xiaodai suggested.

1 Like

You may also want to look at DataStructures.jl which has a SortedDict struct, which will handle this for you.

6 Likes

I needed to sort(collect(pairs(d)), by=x->x[1]). See GitHub - andyferris/Dictionaries.jl: An alternative interface for dictionaries in Julia, for improved productivity and performance .