>>> 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
>>> 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.