开发者

adding new pair in dictionary why the last added 'mynewkey': 'mynewvalue' came first in dictionary [duplicate]

This question already has answers here: 开发者_StackOverflow Why is python ordering my dictionary like so? [duplicate] (3 answers) How to keep keys/values in same order as declared? (13 answers) Closed 9 years ago.
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}

why the last added 'mynewkey': 'mynewvalue' came first in dictionary


Python dictionaries are not ordered. If you iterate over the items of a dict object you will not get them in the order you inserted them. The reason is the internal data structure behind it.

If you use Python 2.7 or Python 3.3 you can resort to http://docs.python.org/dev/library/collections.html#collections.OrderedDict


Dictionaries and sets are unordered in Python. The items end up in an order that varies from Python version to Python version, implementation to implementation, and shouldn't be relied upon.

If you need to keep the items in order, you can use a collections.OrderedDict. For versions of Python older than 2.7, you can download it from PyPI.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜