为什么python字典会更改顺序? [英] Why do python dictionaries change order?

查看:44
本文介绍了为什么python字典会更改顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python3.5中,字典中存储的对象的顺序会随着解释器的不同执行而改变,但对于相同的解释器实例,似乎保持不变.

The order of objects stored in dictionaries in python3.5 changes over different executions of the interpreter, but it seems to stay the same for the same interpreter instance.

$ python3 <(printf 'print({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})')
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
{'b': 2, 'a': 1}
$ python3 <(printf 'print({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})\nprint({"a": 1, "b": 2})')
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}

我一直认为顺序是基于键的哈希值.为什么不同的python执行之间的顺序不同?

I always thought the order was based off of the hash of the key. Why is the order different between different executions of python?

推荐答案

词典使用 hash 函数,并且顺序 is 基于密钥的哈希.

Dictionaries use hash function, and the order is based on the hash of the key all right.

但是,正如此问题与解答,从python 3.3开始,在执行时随机选择哈希值的种子(更不用说它取决于python版本).

But, as stated somewhere in this Q&A, starting from python 3.3, the seed of the hash is randomly chosen at execution time (not to mention that it depends on the python versions) .

请注意,从Python 3.3开始,还使用了随机哈希种子,使得哈希冲突无法预测,以防止某些类型的拒绝服务(攻击者通过引起大量哈希冲突而使Python服务器无响应).这意味着给定字典的顺序也取决于当前Python调用的随机哈希种子.

Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary is then also dependent on the random hash seed for the current Python invocation.

因此,每次执行程序时,您可能会得到不同的命令.

So each time you execute your program, you may get a different order.

由于不保证字典的顺序(无论如何在python 3.6之前也不保证),所以这是您不应该考虑的实现细节.

Since order of dictionaries are not guaranteed (not before python 3.6 anyway), this is an implementation detail that you shouldn't consider.

这篇关于为什么python字典会更改顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆