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

  • Duplicate of [Why is python ordering my dictionary like so?](http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so) and [Python dictionary, keep keys/values in same order as declared](http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in-same-order-as-declared) and [How do you retrieve items from a dictionary in the order that they're inserted?](http://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted) and others. – agf Sep 22 '11 at 11:13

2 Answers2

1

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

rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
1

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.

agf
  • 171,228
  • 44
  • 289
  • 238