Group Students by City
Python
30 pts
Group Students by City
Each tuple below holds a student’s name and city:
students = [("Selam", "Asmara"), ("Abel", "Keren"), ("Merhawi", "Asmara"),
("Lidya", "Massawa"), ("Yonas", "Keren"), ("Ruth", "Asmara")]
- Create a dictionary called
by_citywhere each city is a key and the value is a list of the names from that city. Usesetdefault(). - Then loop through
by_cityand print each city, a colon, the number of students and their names joined with", ", exactly as shown.
Expected output:
Asmara (3): Selam, Merhawi, Ruth Keren (2): Abel, Yonas Massawa (1): Lidya
Checklist
- Group the names by city in
by_city, usingsetdefault(). - Print one line for each city with the count and the names.
🔑 Solution
If you view the solution before passing, you earn half points for this exercise. You still need to type it and press Check to finish.
How it works, step by step
Point at a step to highlight its lines. Type the solution yourself and press Check answer to finish.
