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

Proper way of Initializing dictionary with list?

I am trying to construct a dictionary whose values are lists in the example code below why all the values are not coming for US & UK

cities = {'San Francisco': 'US', 'London': 'UK',
          'Manchester': 'UK', 'Paris': 'France',
          'Los Angeles': 'US', 'Seoul': 'Korea'}

a = {}

for item, key in cities.items():
    a[key] = [item]

print(a)

Current Output

{'US': ['Los Angeles'], 'UK': ['Manchester'], 'France': ['Paris'], 'Korea': ['Seoul']}

Expected Output

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

{'US': ['San Francisco', 'Los Angeles'], 'UK': ['London', 'Manchester'], 'France': ['Paris'], 'Korea': ['Seoul']}

>Solution :

You might use .setdefault method of dict for this task as follows

cities = {'San Francisco': 'US', 'London': 'UK',
          'Manchester': 'UK', 'Paris': 'France',
          'Los Angeles': 'US', 'Seoul': 'Korea'}

a = {}

for item, key in cities.items():
    a.setdefault(key,[]).append(item)

print(a)

output

{'US': ['San Francisco', 'Los Angeles'], 'UK': ['London', 'Manchester'], 'France': ['Paris'], 'Korea': ['Seoul']}

Explanation: If a does not already have key then put [] (empty list). Add item at end of list which is under key.

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