Table of contents
1.
Introduction
2.
Methods to Sort a Dictionary by Value
2.1.
Using sorted() Function
2.1.1.
Syntax
2.1.2.
Example
2.2.
Python
2.3.
Sorting in Ascending and Descending Order
2.3.1.
Ascending Order
2.4.
Python
2.4.1.
Descending Order
2.5.
Python
2.6.
Using For Loop
2.7.
Python
2.8.
Using Bubble Sort
2.9.
Python
2.10.
Using item getter from the operator Module
2.11.
Python
2.12.
Handling Ties in Values
2.13.
Python
2.14.
Sorting Nested Dictionaries
2.15.
Python
3.
Frequently Asked Questions
3.1.
Can I sort a dictionary by key instead of value?
3.2.
How do I sort a dictionary with mixed data types?
3.3.
Is it possible to sort a dictionary in place?
4.
Conclusion
Last Updated: Dec 22, 2024
Medium

Sort a Dictionary by Value in Python

Author Riya Singh
0 upvote

Introduction

A dictionary in Python is a collection of key-value pairs, where each key is unique. Sometimes, you might want to sort these dictionaries based on their values rather than their keys. Sorting a dictionary by value can help you analyze data more effectively. 

Sort a Dictionary by Value in Python

This article will guide you through different methods to sort a dictionary by its values in Python, with simple examples and explanations.

Methods to Sort a Dictionary by Value

Using sorted() Function

The sorted() function can be used to sort a dictionary by its values. The sorted() function returns a sorted list of the specified iterable's items.

Syntax

sorted(iterable, key=None, reverse=False)

 

  • iterable: The sequence to be sorted.
     
  • key: A function that serves as a key for the sort comparison.
     
  • reverse: A Boolean. If True, the sorted list is reversed.

Example

  • Python

Python

# Define a dictionary

my_dict = {'apple': 10, 'banana': 5, 'cherry': 7}


# Sort the dictionary by value

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print("Sorted Dictionary:", sorted_dict)
You can also try this code with Online Python Compiler
Run Code


Output

Sorted Dictionary: {'banana': 5, 'cherry': 7, 'apple': 10}


In this example, the dictionary is sorted by its values in ascending order using a lambda function as the key.

Sorting in Ascending and Descending Order

You can sort a dictionary in both ascending and descending order.

Ascending Order

  • Python

Python

# Sort the dictionary by value in ascending order

sorted_dict_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print("Ascending Order:", sorted_dict_asc)
You can also try this code with Online Python Compiler
Run Code


Output:

Ascending Order: {'banana': 5, 'cherry': 7, 'apple': 10}

Descending Order

  • Python

Python

# Sort the dictionary by value in descending order

sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))

print("Descending Order:", sorted_dict_desc)
You can also try this code with Online Python Compiler
Run Code


Output

Descending Order: {'apple': 10, 'cherry': 7, 'banana': 5}


In the descending order example, the reverse=True argument is added to sort the values in descending order.

Using For Loop

You can sort a dictionary by its values using a for loop by iterating over the dictionary and sorting the key-value pairs manually.

  • Python

Python

# Define the dictionary
my_dict = {'apple': 10, 'orange': 5, 'banana': 20, 'grape': 15}

# Sort the dictionary by value using a for loop
sorted_dict = {}
for key in sorted(my_dict, key=my_dict.get):
sorted_dict[key] = my_dict[key]

# Output the sorted dictionary
print("Sorted dictionary by value:", sorted_dict)
You can also try this code with Online Python Compiler
Run Code

 

Output

Sorted dictionary by value: {'orange': 5, 'apple': 10, 'grape': 15, 'banana': 20}

Using Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent items and swaps them if they are in the wrong order. To sort a dictionary by value, we can implement Bubble Sort on its items.

  • Python

Python

# Define the dictionary
my_dict = {'apple': 10, 'orange': 5, 'banana': 20, 'grape': 15}

# Convert dictionary to a list of tuples (key, value)
dict_items = list(my_dict.items())

# Bubble Sort by value
n = len(dict_items)
for i in range(n):
for j in range(0, n-i-1):
if dict_items[j][1] > dict_items[j+1][1]:
dict_items[j], dict_items[j+1] = dict_items[j+1], dict_items[j]

# Convert the sorted list back to a dictionary
sorted_dict = dict(dict_items)

# Output the sorted dictionary
print("Sorted dictionary by value using Bubble Sort:", sorted_dict)
You can also try this code with Online Python Compiler
Run Code

 

Output

Sorted dictionary by value using Bubble Sort: {'orange': 5, 'apple': 10, 'grape': 15, 'banana': 20}

Using item getter from the operator Module

Another way to sort a dictionary by value is by using itemgetter from the operator module.

Syntax

operator.itemgetter(n)

 

Example

  • Python

Python

from operator import itemgetter

# Define a dictionary

my_dict = {'apple': 10, 'banana': 5, 'cherry': 7}


# Sort the dictionary by value using itemgetter

sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(1)))


print("Sorted Dictionary:", sorted_dict)
You can also try this code with Online Python Compiler
Run Code


Output

Sorted Dictionary: {'banana': 5, 'cherry': 7, 'apple': 10}


In this example, itemgetter(1) is used to sort the dictionary by its values.

Handling Ties in Values

When sorting by values, ties (identical values) may occur. The default behavior is to retain the original order of keys with identical values.

Example

  • Python

Python

# Define a dictionary with ties

my_dict = {'apple': 10, 'banana': 5, 'cherry': 7, 'date': 7}

# Sort the dictionary by value

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print("Sorted Dictionary with Ties:", sorted_dict)
You can also try this code with Online Python Compiler
Run Code


Output

Sorted Dictionary with Ties: {'banana': 5, 'cherry': 7, 'date': 7, 'apple': 10}

Sorting Nested Dictionaries

Sometimes dictionaries contain other dictionaries as values. Sorting these can be a bit more complex but follows the same principles.

Example

  • Python

Python

# Define a nested dictionary

nested_dict = {

   'fruits': {'apple': 10, 'banana': 5},

   'vegetables': {'carrot': 3, 'beetroot': 8}

}

# Sort the nested dictionary by value of the inner dictionary

sorted_nested_dict = {k: dict(sorted(v.items(), key=lambda item: item[1])) for k, v in nested_dict.items()}

print("Sorted Nested Dictionary:", sorted_nested_dict)
You can also try this code with Online Python Compiler
Run Code


Output

Sorted Nested Dictionary: {'fruits': {'banana': 5, 'apple': 10}, 'vegetables': {'carrot': 3, 'beetroot': 8}}

Frequently Asked Questions

Can I sort a dictionary by key instead of value?

Yes, use key=lambda item: item[0] in the sorted() function.

How do I sort a dictionary with mixed data types?

Ensure all values are comparable. Convert values to a common data type if necessary.

Is it possible to sort a dictionary in place?

No, sorting a dictionary returns a new dictionary. The original dictionary remains unchanged.

Conclusion

Sorting a dictionary by value in Python is straightforward with the sorted() function and itemgetter from the operator module. Understanding these methods helps in organizing and analyzing data efficiently. By mastering these techniques, you can enhance your Python programming skills and write more effective code.
You can also practice coding questions commonly asked in interviews on Cod360

Live masterclass