python - 为什么python dict键的顺序不一致?

标签 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/

相关文章:

python - Tensorflow 中的 Theano.function 等价物

python - 设置与frozenset 性能

python - Keras LSTM - 使用生成器中的 Tensorflow 数据集 API 提供序列数据

python - Python中的特殊(魔术)方法

python - 在 Python 中使词形还原器的多重搜索和替换更加精确

python - 从包含字典的单个变量中创建 Pandas 的数据框

python - 从 ManyToMany 在 admin.py 中添加字段

python - 比较忽略特定键的字典

python - 从组合两个多索引 dfs 和列索引的元组列表构建字典

ios - IOS中的排序键