2

Consider a simple script with the following code:

d = {'asdf': 1, 'qwer': 2}
for v in d.keys():
    print(v)

This seems to be deterministic (i.e.: the keys are always printed in the same order in all executions) when executed with a Python 2 interpreter (2.7.10), but not when executed with a Python 3 interpreter (3.5.0).

Could anybody explain what changed?

I know a dictionary is a hash table and, therefore, the keys are sorted "arbitrarily". However, I thought they were not sorted randomly (i.e.: when creating the same dictionary again, it would have the same representation in memory and the .keys() method will return the keys in the same exact arbitrary order.

Also, the Python documentation states (for Python 2 and Python 3):

Keys and values are listed (Python 2)/iterated over (Python 3) in an arbitrary order which is non-random[...]

Am I missing something?

Peque
  • 10,375
  • 7
  • 48
  • 83
  • I also find the same thing, using python 2.7.10 and python 3.5.1. Sometimes, when I check a dict is same in a test case, usingl str(a_dict)=="{'asdf': 1, 'qwer': 2}". But in 3.5.1, sometimes, it pass, sometimes fails. – Colin Ji May 07 '16 at 22:24

0 Answers0