开发者

Items ordering in Python dictionary

开发者 https://www.devze.com 2023-01-05 08:29 出处:网络
I am in simple doubt... I created the following dictionary: >>> alpha={\'a\': 10, \'b\': 5, \'c\': 11}

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:

>>>开发者_如何学Python; 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.


Dictonaries are not guaranting sorting of keys. You can find this information in python docs: http://docs.python.org/tutorial/datastructures.html#dictionaries

You can always sort dictionary keys or use other, more specialized collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号