为什么python会这样订购我的字典? [英] Why is python ordering my dictionary like so?

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

问题描述

这是我的字典

propertyList = {
    "id":           "int",
    "name":         "char(40)",

    "team":         "int",
    "realOwner":    "int",

    "x":            "int",
    "y":            "int",

    "description":  "char(255)",

    "port":         "bool",
    "secret":       "bool",
    "dead":         "bool",
    "nomadic":      "bool",

    "population":   "int",
    "slaves":       "int",
}

但是当我用 " ".join(myDict) 打印出来时,我得到了这个

But when I print it out with " ".join(myDict) I get this

name
nomadic
dead
port
realOwner
secret
slaves
team
y
x
population
id
description

我知道字典是无序的,但每次出来的结果都是一样的,我不知道为什么.

I know that a dictionary is unordered but it comes out the same every time and I've no idea why.

推荐答案

对于旧版本的 Python,真正的问题应该是为什么不呢?"— 无序字典通常实现为 哈希表,其中元素的顺序是明确定义的但不是很明显(用于说明这一点的 Python 文档).您的观察完全符合哈希表的规则:表面上是任意的,但顺序不变.

For older versions of Python, the real question should be "why not?" — An unordered dictionary is usually implemented as a hash table where the order of elements is well-defined but not immediately obvious (the Python documentation used to state this). Your observations match the rules of a hash table perfectly: apparent arbitrary, but constant order.

Python 已更改其 dict 实现以保留插入顺序,并且 这是保证 Python 3.7.因此,该实现不再构成纯哈希表(但在其实现中仍使用哈希表).

Python has since changed its dict implementation to preserve the order of insertion, and this is guaranteed as of Python 3.7. The implementation therefore no longer constitutes a pure hash table (but a hash table is still used in its implementation).

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

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