Q:

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

belongs to collection: Python Lambda Function Programs

0

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}]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Check if value is in a List using Lambda Function ...