为什么Python解释器在将2.0和2用作字典键时认为它们是相同的?

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

Why does python interpreter consider 2.0 and 2 to be the same in an when used as a dictionary key

问题

当我运行这段代码时,输出结果是Python,但我预期会是love。我知道在字典中不能有多个相同的键。但我想知道的是为什么Python解释器将2.02视为相同,并返回2的值。

英文:

I was going through twitter when i came across the function below

def func():
    d = {1: "I", 2.0: "love", 2: "Python"}
    return d[2.0]
print(func())

When i ran the code, i got Python as the output and i expected it to be love. I know that you cannot have multiple key in a dictionary. However what i want to know is why Python Interpreter considers 2.0 and 2 as the same and returns the value of 2

答案1

得分: 4

这里的文档中提到:

相等的数值具有相同的哈希值(即使它们属于不同的类型,就像1和1.0一样)。

英文:

Here in the documentation it says that:

> Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

答案2

得分: 1

在你的例子中,键 2.02 被视为相同,因为它们的哈希值相等。这是因为在Python中,浮点数和整数对象即使具有不同的类型和表示,它们也可以相等。特别地,整数 2 和浮点数 2.0 具有相同的值,因此它们被视为相等。

这就是为什么你应该始终在字典的键中使用一致的类型。请记住始终使用整数或浮点数。

英文:

In your example, the keys 2.0 and 2 are considered the same because their hash values are equal. This is because in Python, float and integer objects can be equal even if they have different types and representations. In particular, the integer 2 and the floating-point number 2.0 have the same value, so they are considered equal.

That's why you should always use consistent types for keys in dictionaries. Always remember to use integers or floats.

huangapple
  • 本文由 发表于 2023年2月16日 03:33:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464645.html
匿名

发表评论

匿名网友

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

确定