Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do dicts preserve iteration order if they are not modified?

If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups).

like image 554
Claudiu Avatar asked Dec 04 '09 20:12

Claudiu


People also ask

Do Python Dicts 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.

Do dictionaries preserve order?

Standard dict objects preserve order in the reference (CPython) implementations of Python 3.5 and 3.6, and this order-preserving property is becoming a language feature in Python 3.7. You might think that this change makes the OrderedDict class obsolete.

Does for loop maintain order?

For lists, yes, since they are ordered data structures in Python.

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.


1 Answers

Here is what dict.items() documentation says:

dict.items() return a copy of the dictionary’s list of (key, value) pairs.

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

I think it's reasonable to assume that item ordering won't change if all you do is iteration.

like image 157
Nikola Smiljanić Avatar answered Sep 22 '22 23:09

Nikola Smiljanić