我正在用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”),它会正确地回复,但是如果我在块中同时有两个,它只会回复第二个结果,因为第一个结果不存在......知道为什么吗?
同样,在终端有时它根本不工作,但在交互式环境是的...为什么???
谢谢
1条答案
按热度按时间ahy6op9u1#
你的问题有些模糊,首先请澄清字典的定义,它是键和值的一一对应关系。
在您的示例中,29是键,4是值。
让我们读一下
get(key[,default])
方法的定义:如果key在字典中,则返回key的值,否则返回default。如果未给定default,则默认为
None
,因此此方法不会引发KeyError。在你的密码里,
第一个函数将返回“key not found”,因为4不是字典
mio_dict
中的键,第二个函数将返回4,因为29是键,其值为4。可以使用debug查看这两行返回的值,也可以使用print()方法查看输出。