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 code to sort list of dictionaries by values using lambda and sorted() function
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer