Create dictionary with multiple values

Question:

I have two lists, one is the list of countries with duplicate items, and the other list is cities in those countries without any duplicate. But both lists are having exact number of items.

List 1:

[USA, USA, CHINA, CANADA, CANADA]

List 2:

[Chicago, NY, Beijing, Vancouver, Toronto]

I want to create a dictionary based on the countries and list the cities inside of it. so something like this:

{ 'USA': ['Chicago','NY'], 'CHINA': ['Beijing'], 'CANADA': ['Vancouver', 'Toronto'] }

How can I do this?

I tried this code:

countries_list = [USA, USA, CHINA, CANADA, CANADA]
cities_list = [Chicago, NY, Beijing, Vancouver, Toronto]

dic = {'Countries': [], 'Cities': []}
for i in countries_list:
  for x in cities_list:
    dic['Countries'].append(i)
    dic['Cities'].append(x)

but it only outputs 1 record.

{'Countries': ['CHINA'], 'Cities': ['Beijing']}
Asked By: Michael S

||

Answers:

By having one loop into another, you’ll get the product of each you’ll have each city on each country, so 5×5 = 25 elements

You need to iterate on both at the same time, use zip, then use dict.setdefault to create a list if missing for the country, and append it the city

countries = ["USA", "USA", "CHINA", "CANADA", "CANADA"]
cities = ["Chicago", "NY", "Beijing", "Vancouver", "Toronto"]
result = {}
for country, city in zip(countries, cities):
    result.setdefault(country, []).append(city)
print(result)
# {'USA': ['Chicago', 'NY'], 'CHINA': ['Beijing'], 'CANADA': ['Vancouver', 'Toronto']}

collections.defaultdict can also be used

from collections import defaultdict
result = defaultdict(list)
for country, city in zip(countries, cities):
    result[country].append(city)
Answered By: azro
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.