问题
Is there a way to reliably fix the order of dictionary handling in Python 3, i.e. establish iteration over keys and values with a predictable order?
For debugging purposes and to reproduce a failure that, supposedly, is based on dictionary access in python 3.3 and 3.4, I need to somehow make the iteration over dictionaries predictable. What I mean is I want to fix the way any iteration is performed at the start of the Python program. Such that starting the program many times, calls to dict.items()
, dict.keys()
, dict.values()
always produce the same order of elements. Even more so, it would be nice to change this order by setting some sort of seed value of the hash function. How can I do this?
This is for debugging only, I don't want and cannot use something like sorted(dict.keys())
or OrderedDict
. Thanks!
回答1:
You should take a look at the PYTHONHASHSEED
environment variable:
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED
Set it to a fixed integer and then your hash seed is deterministic.
来源:https://stackoverflow.com/questions/29275434/how-to-fix-the-order-of-dictionary-handling-in-python-3