Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create dictionary with multiple values

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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']}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading