英文:
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 dict
s 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论