简体   繁体   English

python中的字典顺序

[英]Dictionary order in python

Everywhere I search, they say python dictionary's doesn't have any order.我到处搜索,他们说 python 字典没有任何顺序。 When I run code 1 each time shows a different output (random order).当我每次运行代码 1 时都会显示不同的输出(随机顺序)。 But when I run code 2 it always shows the same sorted output.但是当我运行代码 2 时,它总是显示相同的排序输出。 Why is the dictionary ordered in the second snippet?为什么字典在第二个片段中排序?

   #code 1

    d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
    for a, b in d.items():
        print(a, b)
   #code 2 

    d = {1: 10, 2: 20, 3: 30, 4: 40}
    for a, b in d.items():
        print(a, b)

Outputs产出

code 1:代码 1:

four 4
two 2
three 3
one 1

code 1 again:代码 1 再次:

three 3
one 1
two 2
four 4

code 2 (always):代码 2(始终):

1 10
2 20
3 30
4 40

It's related to how hash randomisation is applied.这与哈希随机化的应用方式有关。 Quoting docs (emphasis mine):引用文档(强调我的):

By default, the __hash__() values of str , bytes and datetime objects are “salted” with an unpredictable random value.默认情况下, strbytesdatetime对象的__hash__()值是用不可预测的随机值“加盐”的。 Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.尽管它们在单个 Python 进程中保持不变,但它们在 Python 的重复调用之间不可预测。

For each subsequent run, your strings (keys in snippet 1) are hashed with different salt value - therefore hash value is also changed.对于每个后续运行,您的字符串(代码段 1 中的键)使用不同的盐值进行哈希处理 - 因此哈希值也会更改。 Hash values determine ordering.哈希值决定顺序。

For int type, hash function never changes - in fact hash is always equal to integer value.对于int类型,哈希函数永远不会改变——实际上哈希总是等于整数值。

assert hash(42) == 42

If hashing function never changes, there is no change in ordering in subsequent runs.如果散列函数永远不会改变,则在后续运行中的排序也不会改变。

For details in how Python dictionaries are implemented, you may refer to How are Python's Built In Dictionaries Implemented . Python字典的具体实现方式可以参考Python内置字典是如何实现的

Not anymore: from Python 3.6 onwards, the standard dict type maintains insertion order by default, see the What's New in Python 3.6 documentation here .不再是:从 Python 3.6 开始,标准dict类型默认保持插入顺序,请参阅此处的 Python 3.6 文档中的新增功能。

Python 3.7 elevated this implementation detail to a language specification , so it is now mandatory that dict preserves order Python 3.7+ Python 3.7 将此实现细节提升为语言规范,因此现在强制要求dict保留顺序 Python 3.7+

(via @Martijn Pieters answer here , and the Python documentation here ) (通过@Martijn Pieters在这里回答,以及这里的 Python 文档)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM