How to Sort a List of Dictionaries by Multiple Keys
How to Sort a List of Dictionaries by Multiple Keys
How to Sort a List of Dictionaries by Multiple Keys
I have a list of dictionaries and I need to sort them based on multiple keys. How can I do this?
solveurit24@gmail.com Changed status to publish February 16, 2025
You can use the sorted() function with a custom key that returns a tuple of the relevant keys.
Code Example:
students = [
{"name": "Alice", "age": 22, "gpa": 3.5},
{"name": "Bob", "age": 20, "gpa": 3.8},
{"name": "Charlie", "age": 21, "gpa": 3.7}
]
sorted_students = sorted(students, key=lambda x: (x["age"], -x["gpa"]))
print(sorted_students)This sorts the list of students primarily by age in ascending order and secondarily by GPA in descending order.
solveurit24@gmail.com Changed status to publish February 16, 2025