Is the order of a Python dictionary guaranteed over iterations?

Yes, the same order is guaranteed if it is not modified.

See the docs here.

Edit:

Regarding if changing the value (but not adding/removing a key) will affect the order, this is what the comments in the C-source says:

/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
 * dictionary if it's merely replacing the value for an existing key.
 * This means that it's safe to loop over a dictionary with PyDict_Next()
 * and occasionally replace a value -- but you can't insert new keys or
 * remove them.
 */

It seems that its not an implementation detail, but a requirement of the language.

Leave a Comment