Is "for key in dict" in python always repeating in a fixed order?

Is python code

for key in dict: ... 

where dict is the dict data type, always iterating in a fixed order using reggard to key ? For example, suppose dict={"aaa":1,"bbb",2} , will the previous code always first key="aaa" and then key="bbb" (or in another fixed order)? Is it possible that the order is random? I am using python 3.3 in ubuntu 13 and suggest that this working environment is not changing. Thanks.

add one: during several runs, the dict variable remains unchanged, i.e. generates once and reads several times.

+6
source share
2 answers

Essentially, a dictionary does not have the order in which it stores keys. Therefore, you cannot rely on an order. (I would not assume that the order will not change, even if the environment is identical).

One of the few reliable ways:

 for key in sorted(yourDictionary.keys()): # Use as key and yourDictionary[key] 

EDIT : response to your comment: Python does not store keys randomly. All documentation states that you should not rely on this order . It depends on how key management is done. What I will say here about your question: if you rely on this order, you are probably doing something wrong. In general, you don’t need to rely on this at all. :-)

+8
source
 CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. 

For more information: http://docs.python.org/2/library/stdtypes.html#dict.items

What else, you can use collections.OrderedDict to make the order fixed.

+4
source

Source: https://habr.com/ru/post/955645/


All Articles