为什么字典似乎被颠倒了?

myf*_*web 1 python dictionary

为什么python中的字典会出现反转?

>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Kyl*_*utz 16

python中的字典(以及一般的哈希表)是无序的.在python中,您可以使用sort()键上的方法对它们进行排序.


Est*_*ber 5

字典没有固有的顺序.您必须滚动自己的有序dict实现,使用有序listtuples或使用现有的有序 dict实现.


Joh*_*ooy 5

Python3.1有一个OrderedDict

>>> from collections import OrderedDict
>>> o=OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])
>>> o
OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])
>>> for k,v in o.items():
...  print (k,v)
... 
one 1
two 2
three 3
four 4
Run Code Online (Sandbox Code Playgroud)