Reputation: 400
I want to create a graph of all the destinations from a point a to b For this i wrote the code
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)
Input:
Bangalore Hyderabad
Bangalore Mangalore 50
Mangalore Hydrabad 40
Bangalore Hyderabad 10000
Bangalore Chennai 4000
Chennai Hyderabad 4000
Output:
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000}, 'Chennai': {'Hyderabad': 4000}}
Expected Output
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000,'Mangalore': 50}, 'Chennai': {'Hyderabad': 4000}}
The problem here is that i am expecting multiple Entries for the key 'Bangalore, but that isn't happening
Upvotes: 0
Views: 36
Reputation: 649
Use this:
graph.setdefault(i, {}).update({j[1]: j[2]})
instead of this:
graph.update({i: {j[1]: j[2]}})
Upvotes: 2