Lesson guide
What this Python exercise practices
Group students by grade is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 19 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 19 minutes
Practice path
Summary
Organize a list of (name, grade) pairs into a dictionary mapping each grade to the sorted list of student names.
Problem statement
You are given a list of pairs (name, grade). Build and return a dictionary where each key is a grade and the corresponding value is a list of names of students who have that grade. Each list of names must be sorted alphabetically. To make tests deterministic, construct the final dictionary with its keys in ascending order (so its string representation is predictable). If the input list is empty, return an empty dictionary.
Task
Given a list of student entries, create a grouped mapping from grade to an alphabetically sorted list of students who have that grade. Ensure the resulting dictionary has keys in sorted order for deterministic representation.
Examples
Group multiple students
Input
group_by_grade([('Alice', 90), ('Bob', 80), ('Charlie', 90)])
Output
{80: ['Bob'], 90: ['Alice', 'Charlie']}
Explanation
Bob has 80; Alice and Charlie have 90. Names within each grade are sorted; keys are ordered ascending.
Input format
A list of tuples (name: str, grade: int).
Output format
A dictionary mapping grade (int) to list of names (list of str).
Constraints
Grades are comparable (ints). Names are strings. The output dictionary must have keys inserted in sorted order for deterministic str representation.
Samples
Sample input 0
group_by_grade([('Zoe', 70), ('Ann', 70)])
Sample output 0
{70: ['Ann', 'Zoe']}
Explanation 0
Both students have grade 70; names sorted alphabetically.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.