Sort list of dictionaries by values using lambda and sorted() function in Python

Learn how to sort the list of dictionaries by values using lambda and sorted() function in Python?
Submitted by IncludeHelp, on March 15, 2022

Given a list of dictionaries, we have to sort it by values using Lambda and sorted() function.

Sorting is the process of arranging data into meaningful order so that you can analyze it more effectively. In the below solution, we will sort a list of dictionaries by using the lambda function and sorted() function. The lambda function is an anonymous function - that means the function which does not have any name. And, the sorted() function returns a sorted list of the specified iterable object.

Example:

Input: 
students = [
    { "Name" : "Prem", "Age" : 23},
    { "Name" : "Shivang", "Age" : 21 },
    { "Name" : "Shahnail" , "Age" : 19 }
]

Output: Sorting by Age
[{'Name': 'Shahnail', 'Age': 19}, {'Name': 'Shivang', 'Age': 21}, {'Name': 'Prem', 'Age': 23}]

Python code to sort list of dictionaries by values using lambda and sorted() function

# Sorting list of dictionaries using
# sorted() with lambda

# List of dictionaries
students = [
    { "Name" : "Prem", "Age" : 23},
    { "Name" : "Shivang", "Age" : 21 },
    { "Name" : "Shahnail" , "Age" : 19 }
]

# Sorting by Age
print ("Sorted list by Age:")
print (sorted(students, key = lambda x: x['Age']))

print()

# sorting by Name and Age both
print ("Sorted list by Name and Age:")
print (sorted(students, key = lambda x: (x['Name'], x['Age'])))

Output:

Sorted list by Age:
[{'Name': 'Shahnail', 'Age': 19}, {'Name': 'Shivang', 'Age': 21}, {'Name': 'Prem', 'Age': 23}]

Sorted list by Name and Age:
[{'Name': 'Prem', 'Age': 23}, {'Name': 'Shahnail', 'Age': 19}, {'Name': 'Shivang', 'Age': 21}]

Python Lambda Function Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.