0

When i use the items() function of dict in python2.7, i found the order of result has been changed. I want to know how it is sorted in dict.items().

a = {'Person':1, 'Education':1}
b = {':Person':1,':Education':1}
c = {'Education':1, 'Person':1, }
d = {':Education':1,':Person':1,}
print(a.items())
print(b.items())
print(c.items())
print(d.items())

output:

[('Person', 1), ('Education', 1)]
[(':Education', 1), (':Person', 1)]
[('Person', 1), ('Education', 1)]
[(':Person', 1), (':Education', 1)]

background: I will reimplement the code with python3.7. So i must keep the order of output the same as before.

  • dictionaries are unordered in python 2.7, there is no 'sorting' for them, this [changed](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) in python 3.6 where they became insertion ordered – Karan Shishoo Mar 18 '21 at 08:20
  • You mean it's arranged in a random way? I ran it several times and the results stayed the same. So it still follows a certain way when it's outputting – luwen pu Mar 18 '21 at 08:27
  • Not that its accessed in a random way, but before python 3.6 when new entries were added to a dictionary they would not always be added onto the 'end' of the dictionary. Once a dictionary is in a certain state the order of its items should remain the same, but to my knowledge there is no pattern as to where a new entry would be added. – Karan Shishoo Mar 18 '21 at 08:35

0 Answers0