How do I Python sort list of dictionaries by a specific key’s value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by the “name” key, it should become:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
How do I Python sort list of dictionaries by a specific key’s value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by the “name” key, it should become:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
Using the sorted()
function with a lambda expression: Here’s an efficient and commonly used method for sorting a list of dictionaries by a specific key. You can leverage Python’s built-in sorted()
function along with a lambda
to define the sorting criterion:
data = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
sorted_data = sorted(data, key=lambda x: x['name'])
print(sorted_data)
This solution is simple and intuitive, making it an excellent choice when you need to Python sort list of dictionaries based on a specific key. Plus, it doesn’t modify the original list, so your data remains intact if you need to use it later.
Another efficient approach is using itemgetter
from the operator
module. It simplifies accessing dictionary values and can slightly improve performance when compared to lambda
. Here’s how it works:
from operator import itemgetter
data = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
sorted_data = sorted(data, key=itemgetter('name'))
print(sorted_data)
This method is particularly useful when you want a cleaner and more optimized way to Python sort list of dictionaries. The itemgetter
function is specifically designed for tasks like this, making it both efficient and elegant.
If you want to modify the original list rather than creating a sorted copy, the sort()
method is a great option. It’s efficient and works directly on the list, saving memory. Here’s an example:
data = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
data.sort(key=lambda x: x['name'])
print(data)
This in-place method is ideal when you’re working with large datasets and need to minimize overhead. Like the other solutions, it’s a reliable way to Python sort list of dictionaries based on a specific key. Just note that it modifies the original list, so use it carefully when the original order matters!