Sorting a List of Dictionaries by Dictionary Value in Python
Sorting a list of dictionaries by the value of a specific key is a common task in Python programming. This allows you to organize the dictionaries in a meaningful order, such as alphabetically by name or numerically by age.
Solution
To sort a list of dictionaries by the value of a specific key, you can use the sorted() function with the key= parameter. This parameter takes a function that extracts the value of the desired key from each dictionary.
Using a Lambda Function
One way to do this is to use a lambda function, which is an anonymous function without a name. For example, to sort the given list of dictionaries by the 'name' key:
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Using operator.itemgetter
Alternatively, instead of defining your own function, you can use the operator.itemgetter function, which provides a convenient way to extract values from objects. For example:
from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
Reverse Sorting
If you want to sort in descending order, you can add the reverse=True argument to the sorted() function:
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
This will return a new list containing the sorted dictionaries. The original list remains unmodified.
The above is the detailed content of How to Sort a List of Dictionaries by Value in Python?. For more information, please follow other related articles on the PHP Chinese website!