Home > Software design >  how to get o/p as {"Chennai": ["Ram", "stephen"], "Mumbai":
how to get o/p as {"Chennai": ["Ram", "stephen"], "Mumbai":

Time:09-17

I am trying to use defaultdict function here but that does not seem to work

s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"} 
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
sorted(d.items())
print(d)

CodePudding user response:

this should work for you:

from collections import defaultdict


s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"} 
d = defaultdict(list)
for k, v in s.items():
    d[v].append(k)

sorted(d.items())
print(d)

Output:

defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})

CodePudding user response:

You are trying to iterate over keys and values simultaneously so you have to use s.items() to get both key-value pairs as tuples: [('Ram', 'Chennai'), ('Laxman', 'Mumbai'), ('stephen', 'Chennai')]

from collections import defaultdict
s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"} 
d = defaultdict(list)
for k, v in s.items():
    d[v].append(k) # Append k instead of v
sorted(d.items())
print(d) # {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']}

CodePudding user response:

You were iterating through key and val of a dict without a call to items(), also the new dict should have keys with city name hence had to interchange in v and k in the for loop. Here is the code:

from collections import defaultdict
s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"} 
d = defaultdict(list)
for k, v in s.items():
    d[v].append(k)
sorted(d.items())
print(d)

Output:

defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})
  • Related