Dictionary order (Is it consistent up to py3.3 unless using -R or PYTHONHASHSEED is set)

Steve D'Aprano steve+python at pearwood.info
Sun May 28 02:39:42 EDT 2017


On Sun, 28 May 2017 10:51 am, Bill Deegan wrote:

> Greetings,
> 
> As a follow up to a discussion on IRC #python channel today.
> 
> Assuming the same order of insertions of the same items to a dictionary
> would the iteration of a dictionary be the same (not as the order of
> insertion, just from run to run) for Python 2.7 up to python 3.3? 

That's not a language promise. The dictionary order is explicitly an
implementation detail.

It might happen to be true by *accident* that different versions of Python give
the same order, but that's not guaranteed, and you cannot rely on it.

Consider that you would have to check every version of Python 2.7 through 3.3,
including minor releases, on every platform you care about (Linux, Mac,
Windows, BSD, etc) in both 32- and 64-bit versions, plus Jython, IronPython,
Stackless, PyPy etc, before making a strong claim that the dictionary order is
consistent.

I've tested a couple of versions:

[steve at ando ~]$ python2.7 -c "print({'ab':1, 'cat':2, 'aardvark':3, 'spam':4})"
{'spam': 4, 'aardvark': 3, 'ab': 1, 'cat': 2}
[steve at ando ~]$ python3.2 -c "print({'ab':1, 'cat':2, 'aardvark':3, 'spam':4})"
{'spam': 4, 'aardvark': 3, 'ab': 1, 'cat': 2}
[steve at ando ~]$ python3.3 -c "print({'ab':1, 'cat':2, 'aardvark':3, 'spam':4})"
{'spam': 4, 'aardvark': 3, 'ab': 1, 'cat': 2}

so that's *weak* evidence that it might be consistent from version to version.
(I would be surprised if it changed in a minor version update, but it could.)
However:

steve at orac ~ $ jython -c "print({'ab':1, 'cat':2, 'aardvark':3, 'spam':4})"
{'ab': 1, 'cat': 2, 'aardvark': 3, 'spam': 4}


> And 
> again at Python 3.6?
> (Also for py 3.3 through 3.5.x if PYTHONHASHSEED=0)
> 
> With python 3.6 having the added benefit of guaranteeing insertion order
> is maintained?

No -- there is no such guarantee for 3.6. The only language promise is that
**kwargs keyword arguments will keep insertion order. That's all.

The Python language still reserves the right to re-order dicts at any time,
including minor bug-fix releases. Maybe some time in the future Python will
guarantee that dicts keep insertion order, but that hasn't happened yet.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list