Python dict is a versatile data structure that allows you to easily store diverse amount of data as key-value pairs, in a compact manner. They can be easily converted into JSON objects and vice versa. While working with Python dictionary, developers may need to sort the key-value pairs by key or value, or both. There are several ways to do this in Python. In this article, we will learn how to sort Python dictionary by value.
How to Sort Python Dictionary By Value
Before we proceed, it is important to note that for Python <3.7, dictionary cannot be sorted, but they can only be sorted during display. Also, they are stored in random order. In Python >=3.7, the key-value pairs are stored in order of insertion.
Let us say you have the following dict in Python.
data = {'a':1, ,'c':2, 'b':3}
Here are the different ways to sort above dictionary by keys as well as value.
1. Using sort()
You can use sort() function in Python to sort a list. We will use it to sort the list of keys of dict. The list of keys is obtained using keys() function readily available for each dict. Then we will use this sorted list to extract the corresponding values from original dictionary, and store each key-value pair in a new dictionary. At the end of it, the new dictionary will contain the sorted key-value pairs.
keys = list(data.keys())
keys.sort()
# sorted dict
sorted_data = {i: data[i] for i in keys}
print(sorted_data) # output is {'a': 1, 'b': 2, 'c': 3}
2. Using sorted()
Python provides sorted() function that returns a sorted list of an iterable object. It sorts string values alphabetically and numbers numerically. It also allows you to mention the sort key or specify a formula for it. Here is an example to sort a dict using its values.
d1={k: v for k, v in sorted(data.items(), key=lambda item: item[1])}
print(d1)
In the above code, we call sorted() function on output of data.items(). data.items() returns a list of tuples where each tuple has a key-value pair. We also specify the key to be the 2nd item in each tuple, that is, the value, and not the key. For this, we use lambda function. The sorted() function returns a list of tuples, that have been sorted by the 2nd item in each tuple.
We use a list comprehension to create key-value pairs out of each tuple and store each of them in a new dictionary.
Here is the output.
{'a': 1, 'c': 2, 'b': 3}
Alternatively, you can call the dict() function to convert the result of sorted() function into dict.
d1=dict(sorted(data.items(), key=lambda item: item[1]))
print(d1) # output is {'a': 1, 'c': 2, 'b': 3}
If you want to reverse sort the dictionary, then mention reverse=True argument in sorted function.
3. Using Numpy
Numpy is a powerful Python library that allows you to easily work with numbers and data. It provides argsort() function that returns a list of indexes that will sort an array.
Here is the code to demonstrate it.
import numpy as np
data = {'a':1,'c':2,'b':3}
keys = list(data.keys())
values = list(data.values())
sorted_value_index = np.argsort(values)
sorted_dict = {keys[i]: values[i] for i in sorted_value_index}
print(sorted_dict)
In the above code, we create 2 lists – keys and values – containing all the keys and values of the dict respectively. Then we call argsort() function on the values list. It returns the list of indexes that will sort this array. We use the same list to extract key as well as corresponding value from keys and values lists, and create a new dict that is sorted.
Here is the output.
{'a': 1, 'c': 2, 'b': 3}
Conclusion
In this article, we have learnt several ways to sort a dictionary. Please note, in all the above cases, the original dictionary cannot be sorted. You can only create a new dictionary with the sorted order of items from the original dictionary. Of course, if you are using Python >=3.7, then the dict stores the items in the order of insertion. So if you want to save time and effort, it is better to store the items in the right order during the creation of dict itself.
Also read:
How to Rename Columns in Pandas
How to Select Rows from DataFrame Based on Column Values
How to Concatenate Two Lists in Python

Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.