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?
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?
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"?
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 Source: https://ru.stackoverflow.com/questions/627032/
All Articles