字典条目被覆盖?

Gla*_*ace 2 python arrays dictionary input python-3.x

我发现某些输入没有存储在 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)
Run Code Online (Sandbox Code Playgroud)

带输入:

3
YYZ SEA 500
YYZ YVR 300
YVR SEA 100
Run Code Online (Sandbox Code Playgroud)

我的程序输出:

{'YYZ': {'YVR': '300'}, 'YVR': {'SEA': '100'}}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

您正在'YYZ'使用替换值覆盖键的值。这是字典的预期行为。我的建议是制作字典列表的值而不是单个项目,所以用这样的东西替换你的分配代码

graph.setdefault(start, []).append({end:cost})
Run Code Online (Sandbox Code Playgroud)

尝试一下,看看这是否适用于您的用例。