代码在Visual Studio代码中以奇怪的方式运行(python)

jhkqcmku  于 2023-01-10  发布在  Python
关注(0)|答案(1)|浏览(146)

我正在用python编写VSC中的一些代码,我注意到一个奇怪的行为:

mio_dict = {"Chiave1": "valore1", "Chiave2": "valore2", 29: 4}

mio_dict.get(4, "key not found")
mio_dict.get(29, "key not found")

基本上,如果我只有mio_dict.get(4,“chiave non trovata”),它会正确地回复,但是如果我在块中同时有两个,它只会回复第二个结果,因为第一个结果不存在......知道为什么吗?
同样,在终端有时它根本不工作,但在交互式环境是的...为什么???
谢谢

ahy6op9u

ahy6op9u1#

你的问题有些模糊,首先请澄清字典的定义,它是键和值的一一对应关系。
在您的示例中,29是,4是
让我们读一下get(key[,default])方法的定义:
如果key在字典中,则返回key的值,否则返回default。如果未给定default,则默认为None,因此此方法不会引发KeyError。
在你的密码里,

mio_dict.get(4, "key not found")
mio_dict.get(29, "key not found")

第一个函数将返回“key not found”,因为4不是字典mio_dict中的键,第二个函数将返回4,因为29是键,其值为4。
可以使用debug查看这两行返回的值,也可以使用print()方法查看输出。

print(mio_dict.get(4, "key not found"))
print(mio_dict.get(29, "key not found"))

相关问题