加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

为什么python词典会改变顺序?

发布时间:2020-12-20 13:17:25 所属栏目:Python 来源:网络整理
导读:存储在 python3.5中的字典中的对象的顺序会改变解释器的不同执行,但对于相同的解释器实例,它似乎保持不变. $python3 (printf 'print({"a": 1,"b": 2})nprint({"a": 1,"b": 2})'){'b': 2,'a': 1}{'b': 2,'a': 1}$python3 (printf 'print({"a": 1,"b": 2})'){
存储在 python3.5中的字典中的对象的顺序会改变解释器的不同执行,但对于相同的解释器实例,它似乎保持不变.

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

我一直以为订单是基于密钥的哈希.为什么python的不同执行之间的顺序不同?

解决方法

字典使用哈希函数,顺序基于密钥的哈希值.

但是,正如this Q&A中所述,从python 3.3开始,哈希的种子在执行时被随机选择(更不用说它取决于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.

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

由于无法保证字典的顺序(不管是在python 3.6之前),这是一个你不应该考虑的实现细节.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读