<分区>
首先,我知道如何处理这种情况。我不是在问如何制作 OrderedDict
。
我在问为什么以相同方式创建的同一个字典可以有不同的键顺序?这背后的逻辑是什么?这不是运行时间无关和环境无关的完全相同的代码吗?是什么改变并使 python 产生了不同的结果?
标签 python dictionary
<分区>
首先,我知道如何处理这种情况。我不是在问如何制作 OrderedDict
。
我在问为什么以相同方式创建的同一个字典可以有不同的键顺序?这背后的逻辑是什么?这不是运行时间无关和环境无关的完全相同的代码吗?是什么改变并使 python 产生了不同的结果?
最佳答案
此行为在 object.__hash__()
中有详细说明的规范;这是为了防止某些类型的恶意输入破坏应用程序:
Note By default, the
__hash__()
values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.
在 Python 3.3 之前,情况并非如此,字典将在同一应用程序的不同运行之间具有相同的顺序。
我回答了一个related question关于禁用此行为,它链接到一些相关的源代码。
关于python - 为什么python dict键的顺序不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859514/