Home > Backend Development > Python Tutorial > How Can I Sort a List of Dictionaries by a Specific Key's Value in Python?

How Can I Sort a List of Dictionaries by a Specific Key's Value in Python?

Barbara Streisand
Release: 2024-12-24 13:54:14
Original
741 people have browsed it

How Can I Sort a List of Dictionaries by a Specific Key's Value in Python?

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}]
Copy after login

Sorting this list by name will result in the following output:

sorted_list = [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
Copy after login

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'])
Copy after login

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'))
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template