Python字典中的项目排序

Tho*_*mas 5 python dictionary

我很怀疑...我创建了以下字典:

>>> alpha={'a': 10, 'b': 5, 'c': 11}
Run Code Online (Sandbox Code Playgroud)

但是,当我想看到我得到的字典键和值时:

>>> alpha
{'a': 10, 'c': 11, 'b': 5}
Run Code Online (Sandbox Code Playgroud)

看到"b"和"c"交换了他们的位置.如何使位置与创建字典时的位置相同?

Nic*_*tin 21

字典是无序容器 - 如果要保留顺序,可以使用collections.OrderedDict(Python 2.7或更高版本),或使用自然保留顺序的其他容器类型.

通常,如果您有一个关心有序检索的访问模式,那么字典就可以解决您没有的问题(快速访问随机元素),同时为您提供一个新问题.