如何在Python 3中固定字典处理的顺序?
是否有一种方法可以可靠地固定Python 3中字典处理的顺序,即以可预测的顺序在键和值上建立迭代?
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?
出于调试目的和重现故障(据说是基于python 3.3和3.4中的字典访问)的原因,我需要以某种方式使对字典的迭代可预测.我的意思是我想修复在Python程序开始时执行任何迭代的方式.这样,多次启动程序,对 dict.items()
, dict.keys()
, dict.values()
的调用始终会产生元素的顺序相同.更重要的是,通过设置哈希函数的某种种子值来更改此顺序将是很好的.我该怎么办?
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?
这仅用于调试,我不希望也不能使用 sorted(dict.keys())
或 OrderedDict
之类的东西.谢谢!
This is for debugging only, I don't want and cannot use something like sorted(dict.keys())
or OrderedDict
. Thanks!
您应该看看 PYTHONHASHSEED
环境变量:
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED
将其设置为固定整数,然后您的哈希种子就具有确定性.
Set it to a fixed integer and then your hash seed is deterministic.