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
{'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.