How to Sort a Dictionary by Value in Python?

How to Sort a Dictionary by Value in Python?

Answer: You can use Python’s in-built sorting() function along with the lambda function to sort a dictionary by value in Python.

Dictionaries in Python are flexible data structures that enable you to store data in pairs of keys and values. Sometimes, the value will be sorted by keys rather than using values. Sorting a dictionary by value will help you keep your data organized to perform tasks.

Why Sort a Dictionary by Value: Sorting dictionaries by value improves data analysis and presentation, making information clearer and more accessible. For example: If you have a dictionary where the keys represent student names and the values represent their grades, sorting the dictionary by grade can help identify the top performers.

Table of Contents:

Methods to Sort a Dictionary by Value in Python

There are multiple methods to perform the sorting operation in a Python dictionary. Some of these methods are explained below with examples:

Method 1: Using sorted() Function to Sort a Dictionary in Python 

The sorted() function sorts a dictionary by its keys or values. You can use ‘sorted(dictionary.items())’, where ‘items()’ will return the key-value pairs as tuples. Then the key-value pair will let you decide whether the data should be sorted by key or value and the Reverse argument will decide whether the data should be sorted in ascending or descending order.

1. Sorting a Dictionary in Ascending Order

Let us see an example: Create a list of students with their name and their respective marks accordingly .grades = {‘Priya’: 85, ‘Roy’: 90, ‘Chahar’: 78, ‘Praveen’: 92}So, now to sort these data by values in ascending order use sorted( ) along with lambda function like this.,

Example:

Python

Output:

Dictionary in Ascending Order Output

You can see, that the dictionary is sorted by values in ascending order.

2. Sorting a Dictionary in Descending Order

To sort the dictionary by values in descending order, simply add the reverse = True argument to the sorted() function.

Example:

Python

Output:

Dictionary in Descending Order output

3. Handling Duplicate Values in a Dictionary

When sorting a dictionary that has duplicate values means it has multiple items with the same value then sorting will retain the same value of the data as it were at first. That is called “stable” sorting.

Example:

Python

Output:

Duplicate Values in a Dictionary Output

Here, you can see that values ‘a’ and value ‘c’ have the same items but their order remains unchanged in the dictionary.

4. Sorting by Key and Value Simultaneously

If you want to sort a dictionary by both key and value, you can do so by customizing the key function even further. For instance, if you want to sort by value first and then by key, you could use.

Example:

Python

Output:

Key and Value Simultaneously Output

The key=lambda item:(-item[1],item[0]) first sorts by value in descending order, and if two items have the same value, it sorts by key in ascending order.

Method 2: Using for loop() to Sort a Dictionary in Python

You can use a for loop() to iterate through the sorted items of a dictionary. First, you sort the dictionary using sorted() on the dictionary.items(), then iterate through the sorted result using a for loop to display the sorted value pairs.

Example:

Python

Output:

Sort a Dictionary in Python output

In this example, the products.items() converts the dictionary to a list of tuples, where each tuple is a product and its price is rupees .lambda item: (item[1], item[0]):item[1] sorts by price in ascending order which is in rupees .item[0] sorts by product name alphabetically if prices are the same. The for loop() then prints the sorted products with their prices in rupees.

Method 3: Using Bubble Sort() to Sort a Dictionary in Python

Let’s take an example of a grocery list. In this example, we will sort a dictionary of grocery items with their prices using Bubble Sort. The items will be sorted first by price in ascending order, and if two items have the same price, they will be sorted by name in alphabetical order.

Example:

Python

Output:

Using Bubble Sort() to Sort a Dictionary in Python Output

First, as we discussed we have to sort by Price. As you can see the list is sorted by price in ascending order. Next, we sort by Name. Then in the Bubble Sort process, the algorithm repeatedly compares adjacent items in the list and swaps them if necessary to maintain the correct order.

Method 4: By Using the Key OrderedDict to Sort a Dictionary in Python

OrderedDict is another method to sort the dictionary . This will maintain the order of the items when we sort the dictionary. When the orderedDict and sorted() function is used together it will sort the items by keeping the order.

Example:

Python

Output:

OrderedDict to Sort a Dictionary in Python Output

The OrderedDict maintains the insertion order of items. After sorting, the dictionary retains the new order of items. The sorted() function is used to sort the items based on price and name.

Method 5: Using NumPy to Sort a Dictionary in Python

NumPy is used to sort a dictionary by scores, this method will maintain the relationship between names and scores. Numpy uses arrays so it will first convert the dictionary into an array and then sort based on the condition.

.Example:

Python

Output:

Using NumPy to Sort a Dictionary in Python Output

As it is NumPy, it first arranges the values in ascending order based on their marks after sorting them the NumPy then converts the arrays back into dictionaries so that it can maintain the key-value relationship.

Conclusion

Sorting can be directly done by using the sorted() function which will allow you to rearrange your data effectively. It will sort your data based on your condition like in ascending or descending and it will also handle duplicate values by retaining the original state. Sorting your dictionary by value will make the data perform efficiently.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner