Sorting a List of Dictionaries
Sorting a list of dictionaries is a common operation in Python, particularly when working with data processing and analysis tasks. Python provides several built-in methods and functions to sort a list of dictionaries based on various criteria.
Sorting by a Single Key
To sort a list of dictionaries by a single key, you can use the sorted()
function and provide a key
parameter that specifies the dictionary key to sort by:
## Example list of dictionaries
employees = [
{"name": "John", "age": 35, "salary": 5000},
{"name": "Jane", "age": 28, "salary": 4500},
{"name": "Bob", "age": 42, "salary": 6000}
]
## Sort the list by the 'name' key
sorted_employees = sorted(employees, key=lambda x: x["name"])
print(sorted_employees)
## Output: [{'name': 'Bob', 'age': 42, 'salary': 6000}, {'name': 'Jane', 'age': 28, 'salary': 4500}, {'name': 'John', 'age': 35, 'salary': 5000}]
Sorting by Multiple Keys
You can also sort a list of dictionaries by multiple keys. To do this, you can provide a tuple of keys to the key
parameter in the sorted()
function:
## Sort the list by 'age' in ascending order and 'salary' in descending order
sorted_employees = sorted(employees, key=lambda x: (x["age"], -x["salary"]))
print(sorted_employees)
## Output: [{'name': 'Jane', 'age': 28, 'salary': 4500}, {'name': 'John', 'age': 35, 'salary': 5000}, {'name': 'Bob', 'age': 42, 'salary': 6000}]
In the example above, the list is first sorted by the age
key in ascending order, and then by the salary
key in descending order.
Sorting with the operator
Module
Alternatively, you can use the operator
module in Python to create a more concise sorting function:
import operator
## Sort the list by 'salary' in descending order
sorted_employees = sorted(employees, key=operator.itemgetter("salary"), reverse=True)
print(sorted_employees)
## Output: [{'name': 'Bob', 'age': 42, 'salary': 6000}, {'name': 'John', 'age': 35, 'salary': 5000}, {'name': 'Jane', 'age': 28, 'salary': 4500}]
The operator.itemgetter()
function allows you to specify the keys to sort by, making the sorting logic more readable and maintainable.
By understanding these sorting techniques, you can efficiently sort large lists of dictionaries in your Python applications.