-3

How do I return each country as the key and a list of cities in that country as the value? Using dictionary and embedded list comprehension? Without using collections

country_city_tuples= [('Netherlands', 'Alkmaar'),
                  ('Netherlands', 'Tilburg'),
                  ('Netherlands', 'Den Bosch'),
                  ('Netherlands', 'Eindhoven'),
                  ('Spain', 'Madrid'),
                  ('Spain', 'Barcelona'),
                  ('Spain', 'Cordoba'),
                  ('Spain', 'Toledo'),
                  ('Italy', 'Milano'),
                  ('Italy', 'Roma')]
freddyvh
  • 11
  • 2

1 Answers1

1

You can do something like this:

my_dict = {item[0]: [subitem for subkey, subitem in country_city_tuples if subkey == item[0]] for item in country_city_tuples}

The output will be like:

{'Netherlands': ['Alkmaar', 'Tilburg', 'Den Bosch', 'Eindhoven'], 'Italy': ['Milano', 'Roma'], 'Spain': ['Madrid', 'Barcelona', 'Cordoba', 'Toledo']}
Jay Patel
  • 2,341
  • 2
  • 22
  • 43