包含(嵌入式)列表理解的字典理解

时间:2019-05-23 12:10:41

标签: python list tuples list-comprehension dictionary-comprehension

如何返回每个国家/地区作为键,并返回该国家/地区中的城市列表作为值?使用字典和嵌入式列表理解?不使用收藏集

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

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

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

输出如下:

{'Netherlands': ['Alkmaar', 'Tilburg', 'Den Bosch', 'Eindhoven'], 'Italy': ['Milano', 'Roma'], 'Spain': ['Madrid', 'Barcelona', 'Cordoba', 'Toledo']}