How to Sort a List of Dictionaries by Key in Python
Sorting a list of dictionaries by a specific key is a common task in Python data processing and handling collections of complex data. Python’s built-in sorted()
function and the list sort()
method, combined with the use of a key
parameter often defined as a lambda
function, make it easy to customize sorting behavior. In this article, you’ll learn how to sort lists of dictionaries by their keys with examples, including ascending and descending order sorts, and multi-level sorting.
Table of Content
Why Sort a List of Dictionaries?
- Organize Data: Make data easier to read or process in a specific order.
- Search Optimization: Sorted data can speed up searching algorithms.
- Display Purposes: Present information ordered by relevant fields like names, dates, or scores.
- Data Analysis: Prepare structured data for reporting or further statistical operations.
Syntax & Structure
# Using sorted() function (returns new sorted list)
sorted_list = sorted(your_list, key=lambda d: d['key_name'])
# Using list's sort() method (sorts in place)
your_list.sort(key=lambda d: d['key_name'])
your_list
: The list of dictionaries to be sorted.key
: A function that extracts the sorting key from each dictionary, commonly alambda
.'key_name'
: The dictionary key to sort by.
Basic Sorting Examples
1. Sort by a Single Key in Ascending Order
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
Output
[
{'name': 'Bob', 'age': 25},
{'name': 'Alice', 'age': 30},
{'name': 'Charlie', 'age': 35}
]
2. Sorting In-Place Using list.sort()
people.sort(key=lambda x: x["name"])
print(people)
Output
[
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
Sorting in Descending Order
Use the reverse=True
Parameter
sorted_people_desc = sorted(people, key=lambda x: x["age"], reverse=True)
print(sorted_people_desc)
Output
[
{'name': 'Charlie', 'age': 35},
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25}
]
Sorting by Multiple Keys
When dictionaries have multiple relevant keys, you can sort by a tuple of keys for hierarchical sorting.
Example: Sort by Age, then by Name
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 25}
]
sorted_people = sorted(people, key=lambda x: (x["age"], x["name"]))
print(sorted_people)
Output
[
{'name': 'Charlie', 'age': 25},
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 30}
]
Comparison Table: sorted()
vs list.sort()
Feature | sorted() |
list.sort() |
Best For |
---|---|---|---|
Return Value | Returns a new sorted list | Sorts the list in place and returns None |
Preserving original vs modifying data |
Usability | Works with any iterable (not just lists) | Only works on lists | General sorting vs performance on list |
Syntax |
|
|
Preference and use case dependent |
Performance | Slower due to creating new list | Faster since it sorts in place | When memory < performance and vice versa |
Useful Tips
- Use
key=lambda x: x['key_name']
to specify the sorting key elegantly. - Remember
reverse=True
to order descendingly. - For complex sorting, define a normal function instead of a
lambda
. - Check keys exist: Handle missing keys or provide defaults to avoid
KeyError
. - Sorting is case sensitive: Use
str.lower
in key if needed (e.g.,key=lambda d: d['name'].lower()
). - For heavy sorting: Consider using
operator.itemgetter()
for potentially better performance.
Conclusion
Sorting a list of dictionaries by key in Python is straightforward using the sorted()
function or the in-place list sort()
method with a key
parameter. Mastering the use of lambda
functions and multi-key sorting will allow you to efficiently organize and manipulate complex data structures with ease.
Comments
Post a Comment