词典条目是否被覆盖? [英] Dictionary entry overwritten?

查看:68
本文介绍了词典条目是否被覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found out that some inputs aren't being stored inside my dictionary in 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'}}

由于字典中没有SEA痕迹,第一行提到YYZ似乎被第二行提到YYZ覆盖.

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?

推荐答案

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

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.

这篇关于词典条目是否被覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆