英文:
Code run in a weird way in Visual Studio code (python)
问题
我正在使用VSC中的Python编写一些代码,并注意到了一个奇怪的行为:
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")
,它会正确回应,但如果我像在代码块中那样同时使用两者,它只会回应第二个结果,因为第一个结果不存在...有什么想法吗?
类似地,在终端中有时不起作用,但在交互式Shell中可以...为什么?
谢谢
英文:
I'm wryting some code in VSC in python, and I've noticed a weird behavior:
mio_dict = {"Chiave1": "valore1", "Chiave2": "valore2", 29: 4}
mio_dict.get(4, "key not found")
mio_dict.get(29, "key not found")
Basically, if I've only mio_dict.get(4, "chiave non trovata"), it replies correctly,
but if I`ve both as in the block, it replies only with the second result, as the first isn't there...any ideas why?
Similarly, in the terminal sometimes it doesn't work at all, but in the interactive shell yes...why???
Thank you
答案1
得分: 0
你的问题有些模糊不清。首先,请澄清**dictionaries**的定义,它是键和值之间的一对一对应关系。
在你的情况下,29是键,4是值。
让我们阅读get(key[,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。
你可以使用调试来查看这两行代码返回的值,或者你可以使用print()
方法来查看输出。
print(mio_dict.get(4, "key not found"))
print(mio_dict.get(29, "key not found"))
英文:
Your question is somewhat vague. First, please clarify the definition of dictionaries, which is a one-to-one correspondence between key and value.
In your case, 29 is key and 4 is value.
Let's read the definition of get(key[,default])
method:
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None
, so that this method never raises a KeyError.
In your codes,
mio_dict.get(4, "key not found")
mio_dict.get(29, "key not found")
The first will return "key not found" because 4 is not a key in the dictionary mio_dict
, the second will return 4 because 29 is a key and it's value is 4.
You can use debug to see the value that these two lines return or you can use method print() to see the output.
print(mio_dict.get(4, "key not found"))
print(mio_dict.get(29, "key not found"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论