Sorting a list of dictionaries based on the value of a specific key is a common task. Let's consider a list of dictionaries with names and ages:
list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
To sort this list by name in ascending order, we can utilize the sorted() function with the key parameter. The key parameter allows us to specify a function that determines the sorting order.
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
In this case, we define a lambda function that extracts the 'name' value from each dictionary and uses that value for sorting. The sorted result will be:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
Alternatively, we can use operator.itemgetter instead of defining a custom function. Itemgetter returns a callable that extracts a specific field from each dictionary.
from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
This also produces the same sorted result as before.
Finally, to sort the list in descending order, we can set reverse=True in the sorted() function.
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
This will sort the list as:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
The above is the detailed content of How Can I Sort a List of Dictionaries in Python by a Specific Key?. For more information, please follow other related articles on the PHP Chinese website!