Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary entry overwritten? [duplicate]

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?

like image 648
Glace Avatar asked May 30 '26 05:05

Glace


1 Answers

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.

like image 187
BowlingHawk95 Avatar answered May 31 '26 19:05

BowlingHawk95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!