Home > Backend Development > Python Tutorial > How to Sort a List of Dictionaries by Value in Python?

How to Sort a List of Dictionaries by Value in Python?

Susan Sarandon
Release: 2024-12-18 14:01:10
Original
770 people have browsed it

How to Sort a List of Dictionaries by Value in Python?

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

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

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

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!

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