How to sort a list of dictionaries by a certain key in Python?
Table of Contants
Introduction
In Python, sorting a list of dictionaries by a specific key is a common task. Each dictionary in the list may have the same keys, and the sorting is done based on the values corresponding to a particular key. This can be achieved using Python’s built-in sorted()
function or the sort()
method along with a key function, such as a lambda function or itemgetter()
from the operator
module.
Sorting a List of Dictionaries by a Certain Key
1. Using the sorted()
Function
The sorted()
function in Python returns a new sorted list from the iterable you provide. You can pass a key function to this function that specifies the criterion for sorting. This is useful for sorting dictionaries by a specific key.
Example:
Output:
In this example, the lambda x: x['age']
expression is used to extract the value of the age
key from each dictionary for sorting.
2. Using operator.itemgetter()
The itemgetter()
function from the operator
module can also be used to retrieve the value of a specified key. This is a more efficient and readable way to sort dictionaries by a key.
Example:
Output:
The itemgetter('age')
retrieves the value of the age
key from each dictionary, making it easier to sort.
Practical Examples
Example 1: Sorting in Reverse Order
You can sort the list in descending order by setting the reverse
parameter of the sorted()
function to True
.
Output:
Example 2: Sorting by Multiple Keys
You can sort by multiple keys by passing a tuple of keys to itemgetter()
.
Output:
Conclusion
Sorting a list of dictionaries in Python by a specific key can be easily achieved using the sorted()
function along with a lambda function or operator.itemgetter()
. The sorted()
function allows flexibility with options for ascending, descending, and multi-key sorting, ensuring that your dictionaries are sorted according to your needs.