Sorting a List of Dictionaries by Dictionary Value in Python
Sorting a list of dictionaries based on the value of a particular key can arise in various programming scenarios. Consider an example list of dictionaries representing individuals and their ages:
input_list = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
Sorting this list by name will result in the following output:
sorted_list = [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
Solution:
Python's sorted() function provides a convenient way to sort data structures by applying a custom sorting rule. To sort a list of dictionaries by a specific key's value, use the key= parameter.
Method 1: Using a Lambda Function
The key= parameter expects a function that takes a dictionary as input and returns the value of the key used for sorting. The following code uses a lambda function:
sorted_list = sorted(input_list, key=lambda d: d['name'])
Method 2: Using itemgetter
As an alternative to defining a lambda function, you can use the operator.itemgetter() function:
from operator import itemgetter sorted_list = sorted(input_list, key=itemgetter('name'))
Sorting in Descending Order
To sort in descending order, specify reverse=True in the sorted() function:
sorted_list = sorted(input_list, key=itemgetter('name'), reverse=True)
The above is the detailed content of How Can I Sort a List of Dictionaries by a Specific Key's Value in Python?. For more information, please follow other related articles on the PHP Chinese website!