ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.