为什么dict上的迭代会改变输出中的键顺序?

2024-04-26 12:34:46 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Why is python ordering my dictionary like so?

为什么要重复这句话

d = {'tors':None,
     'head':None,
     'armr':None,
     'arml':None,
     'legl':None,     
     'legr':None}

for k in d.keys():
    print k

将以不同的顺序输出键:

^{pr2}$

Tags: nonedictionarysoismyheadlikeordering
2条回答

这应该可以做到:

import collections

ordered_d = collections.OrderedDict([('banana', 3),('apple',4),('pear', 1),('orange', 2)])
for k in ordered_d.keys():
    print k

结果是:

^{pr2}$

在python中,dict被实现为散列映射,没有人可以保证密钥的顺序。从文档中

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

如果需要继续订购,请改用collections.OrderedDict。在

相关问题 更多 >