问题描述
我想创建一个从a点到b点的所有目的地的图表。为此,我编写了代码
from sys import stdin
starting,ending=input().split()
startnodes=set()
flights=[]
for line in stdin:
x,y,z=line.split()
flights.append([x,y,int(z)])
startnodes.add(x)
startnodes.add(y)
graph={}
for i in startnodes:
for j in flights:
if i==j[0]:
graph.update({i:{j[1]:j[2]}})
print(graph)
输入:
Bangalore Hyderabad
Bangalore Mangalore 50
Mangalore Hydrabad 40
Bangalore Hyderabad 10000
Bangalore Chennai 4000
Chennai Hyderabad 4000
输出:
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000}, 'Chennai': {'Hyderabad': 4000}}
预期产量
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000,'Mangalore': 50}, 'Chennai': {'Hyderabad': 4000}}
这里的问题是,我期望键“班加罗尔”有多个条目,但这并没有发生
1楼
用这个:
graph.setdefault(i, {}).update({j[1]: j[2]})
代替这个:
graph.update({i: {j[1]: j[2]}})