Sometimes we need to sort an array of objects by a certain key. Python gives us this ability through the sort method. In this blog post we will go through an example to show how to sort an array of objects.
Examples
Suppose we have a list of students and we wish to sort those students by their grades:
Ascending order
students = [
{"name": "Alice", "grade": 85, "age": 20},
{"name": "Bob", "grade": 92, "age": 19},
{"name": "Charlie", "grade": 78, "age": 21}
]
students.sort(key=lambda x: x["grade"])
print(students) # Output: [{'name': 'Charlie', 'grade': 78, 'age': 21}, {'name': 'Alice', 'grade': 85, 'age': 20}, {'name': 'Bob', 'grade': 92, 'age': 19}]
Descending order
students = [
{"name": "Alice", "grade": 85, "age": 20},
{"name": "Bob", "grade": 92, "age": 19},
{"name": "Charlie", "grade": 78, "age": 21}
]
students.sort(key=lambda x: x["grade"], reverse=True)
# Output: [{'name': 'Bob', 'grade': 92, 'age': 19}, {'name': 'Alice', 'grade': 85, 'age': 20}, {'name': 'Charlie', 'grade': 78, 'age': 21}]
Why use lambda?
We use lambda because it is a shorter way than writing an actual function:
def get_student_grade(student):
return student["grade"]
Another reason why we have to use lambda is that we are sorting complex objects. If we were sorting numbers, strings, or other data that is simple, it would be straightforward:
odd_numbers = [3, 7, 5, 1]
odd_numbers.sort()
print(odd_numbers) # [1, 3, 5, 7]