![]() |
Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you’re dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore different methods to achieve this, using widely-used and straightforward approaches. How to Sort a List of Dictionaries by Value?Below, are the methods of How To Sort A List Of Dictionaries By A Value in Python.
Sort A List Of Dictionaries By A Value Using List ComprehensionIn this example, the below code showcases sorting a list of dictionaries by the ‘age’ key using the `sorted` function with a lambda function. The list of dictionaries, `list_of_dicts`, is sorted based on the ‘age’ values, and the result is stored in the variable `sorted_list`. Python3
Output
[{'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}] Sort A List Of Dictionaries By A Value Using
|
from operator import itemgetter list_of_dicts = [{ 'name' : 'Alice' , 'age' : 25 }, { 'name' : 'Bob' , 'age' : 30 }, { 'name' : 'Charlie' , 'age' : 22 }] sorted_list = sorted (list_of_dicts, key = itemgetter( 'age' )) print (sorted_list) |
[{'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
itemgetter
FunctionIn this example, below code demonstrates sorting a list of dictionaries by the ‘age’ key. Using the `sorted` function with a lambda function as the key parameter, the list is sorted based on age values. The final result is a new list of dictionaries containing the same entries but sorted by age.
list_of_dicts = [{ 'name' : 'Alice' , 'age' : 25 }, { 'name' : 'Bob' , 'age' : 30 }, { 'name' : 'Charlie' , 'age' : 22 }] sorted_list = sorted (list_of_dicts, key = lambda x: x[ 'age' ]) sorted_list = [{ 'name' : entry[ 'name' ], 'age' : entry[ 'age' ]} for entry in sorted_list] print (sorted_list) |
[{'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Sorting a list of dictionaries by a specific value is a fundamental skill for any Python programmer. The methods outlined in this article, using the sorted
function with a lambda function, the itemgetter
function from the operator
module, and list comprehension, provide flexible and efficient ways to achieve this task. Choose the method that best fits your coding style and requirements, and feel confident in your ability to organize and manipulate data in Python.
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |