How to fix the order of dictionary handling in Python 3?

ぐ巨炮叔叔 提交于 2021-02-10 11:51:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!