Just curious - I thought dict keys would maintain sequence

Peter Otten __peter__ at web.de
Mon Mar 18 03:52:28 EDT 2013


Chris Angelico wrote:

> On Mon, Mar 18, 2013 at 6:26 PM, Frank Millman <frank at chagford.com> wrote:
>> Hi all
>>
>> I know that you cannot rely on the order of keys in a dictionary, and I
>> am not attempting to do so.
>>
>> Nevertheless, the following surprised me. A program creates a dictionary
>> with a known set of keys. I would have thought that multiple runs of the
>> program would return the keys in the same sequence. As you can see, the
>> results appear to be totally random.
>>
>> Just out of interest, I would appreciate an explanation.
> 
> Mainly, it's just something you utterly cannot depend on, so it's
> allowed to vary based on the phase of the moon, the position of your
> hard drive platters, or anything else it likes. The hashing is
> actually randomized in recent versions of Python as a defense against
> a denial of service attack by generating hash collisions; that's most
> likely what you're seeing there. The dictionary object is not
> deterministic to that extent. :)

If you set the PYTHONHASHSEED environment variable you will see the same 
order for every invocation. Anecdotal evidence:

$ python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'c': '', 'b': '', 'a': '', 'e': '', 'd': ''}
$ python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'a': '', 'c': '', 'b': '', 'e': '', 'd': ''}
$ python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'b': '', 'c': '', 'a': '', 'd': '', 'e': ''}

$ PYTHONHASHSEED=42 python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'e': '', 'd': '', 'a': '', 'c': '', 'b': ''}
$ PYTHONHASHSEED=42 python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'e': '', 'd': '', 'a': '', 'c': '', 'b': ''}
$ PYTHONHASHSEED=42 python3.3 -c'print(dict.fromkeys("abcde", ""))'
{'e': '', 'd': '', 'a': '', 'c': '', 'b': ''}

Only str, byte and datetime keys are affected. See

http://docs.python.org/dev/reference/datamodel.html#object.__hash__
http://docs.python.org/dev/using/cmdline.html#envvar-PYTHONHASHSEED





More information about the Python-list mailing list