在Python字典中排序的项目 [英] Items ordering in Python dictionary
问题描述
>>> alpha = {'a':10,'b':5,'c':11}
但是,当我想看到字典键和值时,我得到:
>>> alpha
{'a':10,'c':11,'b':5}
看到b和c已经换了他们的位置。
字典是无序的容器 - 如果你要保存订单,您可以使用 collections.OrderedDict
(Python 2.7或更高版本),或使用另一种自然的订单保存类型。
一般来说,如果你有一个关心有序检索的访问模式,那么一个字典解决你没有的问题(快速访问随机元素),同时给你一个新的。 >
I am in simple doubt... I created the following dictionary:
>>> alpha={'a': 10, 'b': 5, 'c': 11}
But, when I want to see the dictionary keys and values I got:
>>> alpha
{'a': 10, 'c': 11, 'b': 5}
See that the "b" and "c" has swapped their position. How can I make the position be the same of the moment that the dictionary was created?
Dictionaries are unordered containers - if you want to preserve order, you can use collections.OrderedDict
(Python 2.7 or later), or use another container type which is naturally order-preserving.
Generally if you have an access pattern that cares about ordered retrieval then a dictionary is solving a problem you don't have (fast access to random elements), while giving you a new one.
这篇关于在Python字典中排序的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!