Alex Rivera | Logout

Do dicts preserve iteration order if they are not modified?

Asked 2009-12-04T20:03:08.407
19

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).

Edit
Report

1 Answer

31

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.

answered 2009-12-04T20:21:35.257

Your Answer