Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "for key in dict" in python always iterate in a fixed order?

Does the python code

for key in dict:
    ...

, where dict is a dict data type, always iterate in a fixed order with regrard to key? For example, suppose dict={"aaa":1,"bbb",2}, will the above code always first let 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 let's assume this running environment doesn't change. Thank you.

add one thing: during multiple runs, the variable dict remains unchanged, i.e., generate once and read multiple times.

like image 550
user2384994 Avatar asked Oct 10 '13 06:10

user2384994


People also ask

Does Python dictionary keys maintain order?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

Does Python for in loop preserve order?

Yes, it should, every time, since lists are ordered. If you are iterating over a dict , the order may be different than expected.

Does Python iterate through dictionary in order?

In Python 3.6 and beyond, the keys and values of a dictionary are iterated over in the same order in which they were created.

Do dict Keys return same order?

No, there is no guaranteed order for the list of keys returned by the keys() function. In most cases, the key list is returned in the same order as the insertion, however, that behavior is NOT guaranteed and should not be depended on by your program.


2 Answers

Intrinsically, a dictionary has no order in which it stores it keys. So you can not rely on the order. (I wouldn't assume the order to be unchanged even when 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 in a random fashion. All the documentation says is that, you should not rely on this order. It depends on the implementation how the keys are ordered. What I will say here about your question is: If you are relying on this order, you are probably doing something wrong. In general you should/need not rely on this at all. :-)

like image 159
UltraInstinct Avatar answered Sep 28 '22 08:09

UltraInstinct


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 info:http://docs.python.org/2/library/stdtypes.html#dict.items

What's more, You could use collections.OrderedDict to make the order fixed.

like image 24
atupal Avatar answered Sep 28 '22 07:09

atupal