字典由理解构成的条目顺序

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

Order of entries in a dictionary composed by comprehension

问题

我了解到Python的dict是按插入顺序排序的。然而,以下示例代码打印出的dict似乎具有从运行到运行不同的随机顺序:

DICT = {"1D Hist": 1, "1D Plot": 2}
print(DICT)

dict = {entry for entry in DICT}
print(dict)

为什么会这样?这是否是有意的?

C:\Code>python bug.py
{'1D Hist': 1, '1D Plot': 2}
{'1D Plot', '1D Hist'}

C:\Code>python bug.py
{'1D Hist': 1, '1D Plot': 2}
{'1D Hist', '1D Plot'}

我正在使用Python 3.11.4。

英文:

I read that Python's dicts are ordered by insertion order. However, the following example code prints dict with seemingly random orders varying from run to run:

DICT = {"1D Hist": 1, "1D Plot": 2}
print(DICT)

dict = {entry for entry in DICT}
print(dict)

Why is that? Is that intended?

C:\Code>python bug.py
{'1D Hist': 1, '1D Plot': 2}
{'1D Plot', '1D Hist'}

C:\Code>python bug.py
{'1D Hist': 1, '1D Plot': 2}
{'1D Hist', '1D Plot'}

I am using Pyton 3.11.4.

答案1

得分: 1

你所看到的实际上是有意为之的行为。Python使用PYTHONHASHSEED的值来确定字符串、字节字符串和日期的哈希值。如果你不设置它,每次运行Python时它都会得到一个(希望是不同的)随机值。因此hash('abc')在单个Python执行中会给你一个一致的值,但如果你重新启动Python,它很可能会给你一个不同的值。

你正在创建一个字符串集合。集合没有保证的顺序,它们的内部实现严重依赖于哈希值。

英文:

What you are seeing is, in fact, intentional behavior. Python uses the value of PYTHONHASHSEED to determine the hash value of strings, byte strings, and dates. If you do not set it, it will get a (hopefully different) random value each time you run Python. Hence hash('abc') will give you a consistent value within a single Python execution, but is likely to give you a different value if you restart Python.

You are creating a set of strings. Sets have no guaranteed order, and their internal implementation depends heavily on hash values.

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

发表评论

匿名网友

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

确定