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

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

DDD
Release: 2024-12-31 12:49:14
Original
561 people have browsed it

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

Sorting Dictionaries in Python

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

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

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

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

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

This will sort the list as:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template