← All Exercises

Python Sorted with Key Function

intermediatepython~15min

Background

Custom key functions enable complex sorting criteria without implementing full comparison functions.

Problem

Write a function that sorts a list of student dictionaries by grade (descending) and then by name (ascending) using a key function.

Input

A list of student dictionaries with name and grade keys.

Output

A sorted list by grade descending, then name ascending.

Sample tests

Sample 1

Input: [{name:"Bob",grade:85},{name:"Alice",grade:90},{name:"Carol",grade:90}]
Expected: [Alice(90), Carol(90), Bob(85)]

Your solution

Learning objective

Learn multi-criteria sorting with tuple keys and the negation trick for mixed sort directions.