如何获得 o/p 作为 {"Chennai": ["Ram", "stephen"], "Mumbai": "Laxman"} 对于给定的 i/p = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"}
how to get o/p as {"Chennai": ["Ram", "stephen"], "Mumbai": "Laxman"} for given i/p = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"}
我在这里尝试使用 defaultdict 函数,但它似乎不起作用
s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"}
d = defaultdict(list)
for k, v in s:
d[k].append(v)
sorted(d.items())
print(d)
这应该适合你:
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)
输出:
defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})
您正在尝试同时迭代键和值,因此您必须使用 s.items()
将两个键值对作为元组获取:[('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']}
您正在遍历 dict
的 key
和 val
而没有调用 items()
,而且新的 dict
应该有 keys
与城市名称因此必须在 for
循环中的 v
和 k
中互换。这是代码:
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)
输出:
defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})
我在这里尝试使用 defaultdict 函数,但它似乎不起作用
s = {"Ram": "Chennai", "Laxman": "Mumbai", "stephen": "Chennai"}
d = defaultdict(list)
for k, v in s:
d[k].append(v)
sorted(d.items())
print(d)
这应该适合你:
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)
输出:
defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})
您正在尝试同时迭代键和值,因此您必须使用 s.items()
将两个键值对作为元组获取:[('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']}
您正在遍历 dict
的 key
和 val
而没有调用 items()
,而且新的 dict
应该有 keys
与城市名称因此必须在 for
循环中的 v
和 k
中互换。这是代码:
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)
输出:
defaultdict(<class 'list'>, {'Chennai': ['Ram', 'stephen'], 'Mumbai': ['Laxman']})