为什么python会像这样订购我的字典?

Tei*_*ion 41 python dictionary

这是我的字典

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",
}
Run Code Online (Sandbox Code Playgroud)

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

name
nomadic
dead
port
realOwner
secret
slaves
team
y
x
population
id
description
Run Code Online (Sandbox Code Playgroud)

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

Kon*_*lph 79

真正的问题应该是"为什么不呢?"...无序字典最有可能实现为哈希表(事实上​​,Python 文档完全陈述这一点),其中元素的顺序是明确定义的,但不是立即明显的.您的观察完全符合哈希表的规则:明显的任意,但是不变的顺序.


CMS*_*CMS 10

内置字典类型的规范不保留任何顺序,最好将字典视为无序的key: value一对对...

您可能需要检查OrderedDict模块,该模块是具有密钥插入顺序的有序字典的实现.


Mil*_*les 8

您可以依赖的字典排序唯一的事情是,如果没有对字典进行修改,顺序将保持不变; 例如,在不修改字典的情况下迭代字典两次将导致相同的键序列.但是,尽管Python字典的顺序是确定性的,但它可能会受到插入顺序和删除等因素的影响,因此相同的字典最终会有不同的顺序:

>>> {1: 0, 2: 0}, {2: 0, 1: 0}
({1: 0, 2: 0}, {1: 0, 2: 0})
>>> {1: 0, 9: 0}, {9: 0, 1: 0}
({1: 0, 9: 0}, {9: 0, 1: 0})
Run Code Online (Sandbox Code Playgroud)