Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort a dictionary in Python by values?
Python allows dictionaries to be sorted using the built-in sorted() function. In this article, we will explore different ways to sort a dictionary in Python by its values.
Using itemgetter() Method
The itemgetter() method from the operator module provides an efficient way to sort dictionaries by values. It returns a callable object that fetches an item from its operand using the provided index ?
from operator import itemgetter
dictionary = {
'b': 2,
'a': 1,
'd': 4,
'c': 3
}
# Sorting by values using itemgetter
sorted_dict = dict(sorted(dictionary.items(), key=itemgetter(1)))
print(sorted_dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using Lambda Function
A lambda function provides a concise way to sort dictionaries by values. The lambda expression accesses the value part of each key-value pair ?
dictionary = {
'b': 2,
'a': 1,
'd': 4,
'c': 3
}
# Sorting dictionary by values using lambda
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
print(sorted_dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Sorting in Descending Order
To sort dictionary values in descending order, add the reverse=True parameter to the sorted() function ?
dictionary = {
'b': 2,
'a': 1,
'd': 4,
'c': 3
}
# Sorting in descending order
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)
{'d': 4, 'c': 3, 'b': 2, 'a': 1}
Using OrderedDict
The OrderedDict from the collections module was useful in Python versions before 3.7 to maintain insertion order. Modern Python dictionaries maintain order by default ?
from collections import OrderedDict
dictionary = {
'b': 2,
'a': 1,
'd': 4,
'c': 3
}
# Using OrderedDict (mainly for compatibility)
sorted_dict = OrderedDict(sorted(dictionary.items(), key=lambda item: item[1]))
print(sorted_dict)
print(type(sorted_dict))
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
<class 'collections.OrderedDict'>
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
itemgetter() |
Good | Fastest | Performance-critical applications |
| Lambda function | Excellent | Good | General use cases |
OrderedDict |
Good | Good | Legacy Python versions |
Conclusion
Use lambda functions for readable code in most cases. Choose itemgetter() for better performance with large datasets. Modern Python dictionaries maintain order automatically, making OrderedDict less necessary.
