Python
Dictionary
Sorting
Programming
Data Structures

How do I sort a dictionary by value?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Sorting a dictionary by its values is a common task in programming when you want to process data based on the values rather than the keys. In Python, this can be efficiently achieved by using built-in functions and methods. In this article, we will explore how you can sort a dictionary by value using different techniques, provide examples to illustrate each method, and discuss some important considerations when performing these operations.

Understanding Dictionaries in Python

Before diving into sorting, let's briefly review what a dictionary is in Python. A dictionary is a collection of key-value pairs, which are unordered, changeable, and indexed. Unlike sequences (e.g., lists or tuples), dictionaries are optimized for looking up keys quickly.

python
example_dict = {'apple': 2, 'banana': 3, 'cherry': 1}

Sorting by Value

To sort dictionaries by value in Python, you will mainly use the sorted() function, which returns a new sorted list from the elements of any iterable.

Method 1: Using sorted() with a Lambda Function

You can sort a dictionary by value by converting it into a list of tuples and using a lambda function as the key for sorting:

python
1example_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
2sorted_items = sorted(example_dict.items(), key=lambda item: item[1])
3sorted_dict = dict(sorted_items)
4
5print(sorted_dict)
6# Output: {'cherry': 1, 'apple': 2, 'banana': 3}

Explanation:

  • example_dict.items() provides a view object displaying a list of dictionary's key-value tuple pairs.
  • sorted() function sorts these tuples based on the second element, accessed via item[1] in the lambda.

Method 2: Using operator.itemgetter

The operator module provides a more efficient way to sort by value using itemgetter.

python
1from operator import itemgetter
2
3example_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
4sorted_items = sorted(example_dict.items(), key=itemgetter(1))
5sorted_dict = dict(sorted_items)
6
7print(sorted_dict)
8# Output: {'cherry': 1, 'apple': 2, 'banana': 3}

Explanation:

  • itemgetter(1) is similar to lambda function lambda item: item[1], providing a quick and efficient way to fetch the second element of tuples.

Method 3: Using collections.OrderedDict (Python < 3.7)

Although dictionaries maintain order as of Python 3.7, in earlier versions, you could use collections.OrderedDict to maintain the sorted order.

python
1from collections import OrderedDict
2
3sorted_items = sorted(example_dict.items(), key=lambda item: item[1])
4ordered_dict = OrderedDict(sorted_items)
5
6print(ordered_dict)
7# Output: OrderedDict([('cherry', 1), ('apple', 2), ('banana', 3)])

Additional Considerations

  • Stability: The sorting algorithms used in Python guarantee that when multiple records have the same key, their original order will be preserved in the output.
  • Performance: Sorting operations have a time complexity of O(nlogn)O(n \log n), which is an important consideration for large datasets.
  • Reverse Sorting: You can sort values in descending order by specifying the reverse parameter.
python
1sorted_items_desc = sorted(example_dict.items(), key=lambda item: item[1], reverse=True)
2sorted_dict_desc = dict(sorted_items_desc)
3
4print(sorted_dict_desc)
5# Output: {'banana': 3, 'apple': 2, 'cherry': 1}

Summary Table

MethodProsCons
Lambda FunctionSimple, intuitiveSlightly verbose
operator.itemgetterEfficient, conciseLess intuitive for beginners
collections.OrderedDictMaintains order (Pre-3.7)Extra import required

Conclusion

Sorting a dictionary by value is a practical task that can be accomplished in various ways depending on your needs. The choice of method may depend on your specific use case, code readability, or performance needs. Understanding these basic techniques will empower you to manipulate and analyze dictionary data more effectively in Python.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.