I found out that some inputs aren't being stored inside my dictionary in Python 3.
Running this code:
N = int(input()) #How many lines of subsequent input
graph = {}
for n in range (N):
start, end, cost = input().split()
graph[start] = {end:cost}
#print("from", start, ":", graph[start])
print(graph)
with input:
3
YYZ SEA 500
YYZ YVR 300
YVR SEA 100
My program outputs:
{'YYZ': {'YVR': '300'}, 'YVR': {'SEA': '100'}}
It seems like the first line mentioning YYZ was overwritten by the second line mentioning YYZ as there is not trace of SEA inside the dictionary.
What is causing this problem and how can I fix it?
You are overwriting the value for key 'YYZ' with a replacement value. This is expected behavior for dictionaries. My advice would be to make the values of the dictionary lists rather than single items, so replace your assignment code with something like this
graph.setdefault(start, []).append({end:cost})
Try that and see if that will work with your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With