How do I sort a dictionary by key or value?

Better Stack Team
Updated on January 26, 2023

To sort a dictionary by key in Python, you can use the sorted function, like this:

 
d = {"a": 1, "b": 2, "c": 3}
sorted_d = sorted(d.items(), key=lambda x: x[0])

sorted_d will now be a list of tuples, sorted by the key of each tuple.

If you want to sort the dictionary by value, you can use the following code:

 
d = {"a": 1, "b": 2, "c": 3}
sorted_d = sorted(d.items(), key=lambda x: x[1])

This will give you a list of tuples, sorted by the value of each tuple.

You can also use the OrderedDict class from the collections module to sort a dictionary by key or value. To do this, you can use the sorted function to create a sorted list of keys or values, and then use the OrderedDict constructor to create an OrderedDict from the sorted list.

For example:

 
from collections import OrderedDict

d = {"a": 1, "b": 2, "c": 3}
sorted_d = OrderedDict(sorted(d.items(), key=lambda x: x[0]))

This will create an OrderedDict with the keys sorted in ascending order.

You can also use the sort_by_key and sort_by_value functions from the dicttoolz library to sort dictionaries by key or value, respectively.

 
from dicttoolz import sort_by_key, sort_by_value

d = {"a": 1, "b": 2, "c": 3}
sorted_d = sort_by_key(d)

This will return a new dictionary with the keys sorted in ascending order.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →