# How do I sort a dictionary by its keys?

**URL:** <https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848>\
**Category:** New to Julia\
**Tags:** sort, dictionary, dictionaries\
**Created:** [April 19, 2020, 1:20pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848 "2020-04-19T13:20:48Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![NightMachinary](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nightmachinary/32/14196_2.png) [@NightMachinary](https://discourse.julialang.org/u/NightMachinary)\
**Post date:** [April 19, 2020, 1:20pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/1 "2020-04-19T13:20:48Z")

</div>

I want to sort this by its keys:

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

```

---

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [April 19, 2020, 1:29pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/2 "2020-04-19T13:29:47Z")

</div>

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

For normal Dictionaries

```julia
dict = Dict(i => rand() for i in 1:5)
sort(collect(dict), by = x->x[1])

```

---

<div class="post-metadata">

**Author:** ![NightMachinary](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nightmachinary/32/14196_2.png) [@NightMachinary](https://discourse.julialang.org/u/NightMachinary)\
**Post date:** [April 19, 2020, 1:50pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/3 "2020-04-19T13:50:30Z")

</div>

> [@xiaodai](#):
>
> sort(collect(dict), by = x-\>x[1])

```julia
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))

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 19, 2020, 2:17pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/4 "2020-04-19T14:17:21Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Duane\_Wilson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/duane_wilson/32/9506_2.png) [@Duane\_Wilson](https://discourse.julialang.org/u/Duane_Wilson)\
**Post date:** [April 19, 2020, 7:22pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/5 "2020-04-19T19:22:54Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![NightMachinary](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nightmachinary/32/14196_2.png) [@NightMachinary](https://discourse.julialang.org/u/NightMachinary)\
**Post date:** [April 20, 2020, 3:02pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/6 "2020-04-20T15:02:03Z")

</div>

> [@xiaodai](#):
>
> dict = Dict(i =\> rand() for i in 1:5) sort(collect(dict), by = x-\>x[1])

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](https://github.com/andyferris/Dictionaries.jl) .

---

<div class="post-metadata">

**Author:** ![paalon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paalon/32/5784_2.png) [@paalon](https://discourse.julialang.org/u/paalon)\
**Post date:** [June 3, 2024, 4:18am UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/7 "2024-06-03T04:18:14Z")

</div>

If someone need to make an ordered dictionary, it is a bit better to sort then create the ordered dictionary.

```julia
using OrderedCollections
using BenchmarkTools

unordered = Dict(i => rand() for i = 1:1000)

@btime begin
    sorted = OrderedDict(unordered)
    sort!(sorted)
 end
# 68.958 μs (24 allocations: 113.55 KiB)

@btime ordered = OrderedDict(sort(collect(unordered), by=x->x[1]))
# 60.121 μs (22 allocations: 112.92 KiB)

```

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [June 3, 2024, 5:50am UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/8 "2024-06-03T05:50:26Z")

</div>

You can save an allocation and a little time by sorting the collected vector in place

```julia
ordered = OrderedDict(sort!(collect(unordered), by=x->x[1]))

```

and a slight amount of typing with

```julia
ordered = OrderedDict(sort!(collect(unordered), by=first))

```

---

<div class="post-metadata">

**Author:** ![jar1](https://avatars.discourse-cdn.com/v4/letter/j/c0e974/32.png) [@jar1](https://discourse.julialang.org/u/jar1)\
**Post date:** [July 27, 2024, 10:02pm UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/9 "2024-07-27T22:02:54Z")

</div>

```julia
using Dictionaries
julia> let d = Dictionary(rand(5), rand(5))
           getindices(d, sortperm(keys(d))) 
       end
5-element Dictionary{Float64, Float64}
 0.3303619285549789 │ 0.6295079531224393
 0.6532413238779383 │ 0.25149701734258545
   0.74806859304317 │ 0.8964936651264518
 0.9116373283422051 │ 0.011738639576267418
 0.9131045316602528 │ 0.5310761199500899

```

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [July 28, 2024, 8:44am UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/10 "2024-07-28T08:44:00Z")

</div>

In Julia 1.10.4, by simply doing: `sort(d, by=first)`, it outputs an `OrderedCollections.OrderedDic` object:

```julia
d = Dict(1:5 .=> rand(5))
sort(d, by=first)

```

PS:  
The package OrderedCollections.jl is not installed.

---

<div class="post-metadata">

**Author:** ![giordano](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/giordano/32/2166_2.png) [@giordano](https://discourse.julialang.org/u/giordano)\
**Post date:** [July 28, 2024, 8:59am UTC](https://discourse.julialang.org/t/how-do-i-sort-a-dictionary-by-its-keys/37848/11 "2024-07-28T08:59:15Z")

</div>

If the package `OrderedCollections` is doing that, that sounds like type piracy. _ **Edit** _: that’s indeed the case: [Type piracy? · Issue #25 · JuliaCollections/OrderedCollections.jl · GitHub](https://github.com/JuliaCollections/OrderedCollections.jl/issues/25)
