Reg = {5: 1, 6: 2, 7: 3, 8: 4} print Reg.values() 

Conclusion:

 [4, 1, 3, 2] 

Do I understand correctly that the values ​​should go in order?

  • Do I understand correctly that the values ​​should go in order? - Alexander Golubev
  • one
    You do not understand correctly. The dictionary is unpredictable, so come up with collections.OrderedDict - MaxU

2 answers 2

Python dictionaries are unordered. Depending on the specific implementation / version of the language, the order in which the values ​​are defined, and the environment variables ( PYTHONHASHSEED ), the output order may change even for identical dictionaries from start to start.

The current implementation in Python 3.6 and Pypy (Python implemented in RPython) provides ordered dictionaries, but you should not count on it — this implementation detail is not guaranteed by the language specification: other / past / future implementations of Python may use unordered dictionaries.

Use collections.OrderedDict() to preserve the insertion order:

 >>> from collections import OrderedDict >>> OrderedDict(zip("abc", range(5))) OrderedDict([('a', 0), ('b', 1), ('c', 2)]) >>> _.values() [0, 1, 2] 

On Python 3.6, the order of named parameters is preserved:

 >>> OrderedDict(a=0, b=1, c=2) OrderedDict([('a', 0), ('b', 1), ('c', 2)]) 

But such syntax is not required to maintain order in Python 2.7

Related question: Items in JSON object are out of order using "json.dumps"?

  • as far as I noticed, the dictionaries in Python 2.7 are ordered by hashes , in particular, string ordering is observed alphabetically, but this is just a side effect of the implementation — if you change the hashing function, everything can change as it wants. - Dmitry Ponyatov
  • The @DmitryPonyatov order may depend on the history of the dictionary (as elements were added, deleted) and other implementation details that may change even in the bugfix release. Moreover, CPython is not the only Python implementation. There are possible implementations of the dictionary interface, in which the order hash is not connected in any way. Documentation does not promise any order - one should not count on any order. - jfs

Regular dictionary does not guarantee the order of the elements

Use collections.OrderedDict :

 In [22]: from collections import OrderedDict In [23]: Reg Out[23]: {5: 1, 6: 2, 7: 3, 8: 4} In [24]: oReg = OrderedDict(sorted(Reg.items(), key=lambda t: t[1])) In [25]: print(oReg) OrderedDict([(5, 1), (6, 2), (7, 3), (8, 4)]) In [26]: print(oReg.values()) odict_values([1, 2, 3, 4]) In [27]: oReg[6] Out[27]: 2