Home > database >  Proper way of Initializing dictionary with list?
Proper way of Initializing dictionary with list?

Time:12-28

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

CodePudding user response:

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.

CodePudding user response:

What you're doing is overriding the value for each key every time you encounter it. To fix this, check if there's an existing element, and if so, append instead of overwrite.

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

a = {}

for item, key in cities.items():
    if key not in a:
        a[key] = [item]
    else:
        a[key].append(item)

print(a)
  • Related