Key order in another Python dict ()

Possible duplicate:
Python dictionary, keep keys / values ​​in the same order as declared

If in a particular program there are two different dictionaries with the same keys (but different values), will .keys () be in the same order? I did some tests, and it seems to be so, but, not knowing how the internal units of the dictate are, I am not sure if this is guaranteed.

Thanks,

+2
source share
5 answers

You cannot generally rely on the order of keys:

>>> {1: None, 9: None} {1: None, 9: None} >>> {9: None, 1: None} {9: None, 1: None} >>> {1: None, 2: None} {1: None, 2: None} >>> {2: None, 1: None} {1: None, 2: None} 

Dictionaries are disordered. In Python 2.7, collections.OrderedDict exists.

+10
source

It is not guaranteed by the Python language.

The implementation of the CPython interpreter may have returned the keys in the same order in some previous versions, but to fix the security vulnerability this is not very much guaranteed in current and future versions.

+3
source

The policy of storing keys / elements in the same order does not apply between two different dictionary objects and should not be considered saved.

+2
source

If order is important, you should use OrderedDict : http://docs.python.org/dev/library/collections.html#collections.OrderedDict . The order of keys in a dictionary can change when key-value pairs are inserted or deleted.

In addition, the order may vary depending on different Python implementations, so you cannot rely on the same order.

+1
source

Python regular dictionaries are not ordered, and you cannot rely on the order of keys.

In Python 2.7, they introduced OrderedDict. This object stores the keys in the order in which they were inserted.

If you are using Python 2.6 or less, you can have the same functionality using http://pypi.python.org/pypi/ordereddict

0
source

All Articles