`get(key, value)` 返回正确的值,即使你在值的位置上输入错误的值。

huangapple go评论77阅读模式
英文:

why get(key, value) returns the correct value even if you type in the wrong value into the value spot?

问题

我知道这个方法是做什么的,但我试图理解它为什么这样做。例如:

dic = {'a': 500, 'b': 600}

dic.get('a', 5)

#输出

500

我本来以为这会是无效的,但它似乎只是打印出了正确的值,而不是我输入的错误值。为什么会这样,或者是我漏掉了什么其他的东西?谢谢!

英文:

so I know what this method does, but i am trying to understand why it does this. For example:

dic = {'a':500, 'b':600}

dic.get('a', 5)

#output

500

i would expect this to be invalid. but it seems to just print the correct value instead of the incorrect value i typed. why does this do that, or is there something else happening that i am missing. Thanks!

答案1

得分: 1

如果您阅读dict.get的文档,您将看到第二个参数是在字典中不存在键时返回的。

例如:

my_dict = {"a": 100, "b": 200}
print(my_dict.get("a", 200))  # 100
print(my_dict.get("c", 300))  # 300
print(my_dict["c"])           # 引发KeyError
英文:

If you read the docs for dict.get you will see that the second argument is meant to be returned if there is no key present in the dictionary.

For example:

my_dict = {"a": 100, "b": 200}
print(my_dict.get("a", 200))  # 100
print(my_dict.get("c", 300))  # 300
print(my_dict["c"])           # raised KeyError

答案2

得分: 0

dict.get()接受一个键和一个可选的值参数,如果未找到键,则返回该值,不与键的值进行比较。我不知道为什么你_会_想这样使用它,但你可以使用这个来获取你的结果:

dic = {'a': 500, 'b': 600}

key, value = 'a', 5
result = dic.get(key)

if result is None or result != value:
    print("Key value pair not found.")
英文:

dict.get() takes a key and optional value parameter, which is returned if the key is not found and does not compare it to the value of the key. I don't know why you would want to use it like that, but you could use this to get your result:

dic = {'a': 500, 'b': 600}

key, value = 'a', 5
result = dic.get(key)

if result is None or result != value:
    print("Key value pair not found.")

huangapple
  • 本文由 发表于 2023年3月7日 15:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定