Standard library · 9 / 17 Exercise Medium

Cities by country

Objective

Create a Python program that groups cities by country using defaultdict.

Instructions

  • Import defaultdict from the collections module.
  • Read an integer n and then n lines with the format country city (a single word each).
  • Group the cities of each country in a defaultdict(list).
  • Show one line per country, sorted alphabetically, with the format country: city1, city2, with the cities also sorted alphabetically.
Input
5
españa madrid
francia paris
españa sevilla
italia roma
francia lyon
Output
españa: madrid, sevilla
francia: lyon, paris
italia: roma

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise