Skip to main content
 首页 » 编程设计

python之字典条目被覆盖

2025年05月04日19webabcd

<分区>

我发现在 Python 3 中有些输入没有存储在我的字典中。

运行这段代码:

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) 

输入:

3 
YYZ SEA 500 
YYZ YVR 300 
YVR SEA 100 

我的程序输出:

{'YYZ': {'YVR': '300'}, 'YVR': {'SEA': '100'}} 

似乎第一行提到 YYZ 被第二行提到 YYZ 覆盖了,因为字典中没有 SEA 的踪迹。

是什么导致了这个问题,我该如何解决?