Why is python ordering my dictionary like so? [dup

2018-12-31 05:01发布

This question already has an answer here:

Here is the dictionary I have

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",
}

But when I print it out with "\n".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.

3条回答
深知你不懂我心
2楼-- · 2018-12-31 05:09

The specification for the built-in dictionary type disclaims any preservation of order, it is best to think of a dictionary as an unordered set of key: value pairs...

You may want to check the OrderedDict module, which is an implementation of an ordered dictionary with Key Insertion Order.

查看更多
看风景的人
3楼-- · 2018-12-31 05:14

The only thing about dictionary ordering you can rely on is that the order will remain the same if there are no modifications to the dictionary; e.g., iterating over a dictionary twice without modifying it will result in the same sequence of keys. However, though the order of Python dictionaries is deterministic, it can be influenced by factors such as the order of insertions and removals, so equal dictionaries can end up with different orderings:

>>> {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})
查看更多
泛滥B
4楼-- · 2018-12-31 05:19

The real question should be “why not?” … an unordered dictionary is most probably implemented as a hash table (in fact, the Python documentation states this outright) where the order of elements is well-defined but not immediately obvious. Your observations match the rules of a hash table perfectly: apparent arbitrary, but constant order.

查看更多
登录 后发表回答