2

I know that the dictionary in Python is unordered. But I'm confused why my dict is always ordered when I output them. Like the code following, no matter how I change the keys or the values, it is always printed in order. Thank you!

num1 = 30
num2 = 192
c1 = 'good'
c2 = 'hello'
a = {'a':8, 'k':c2, 'c':3, 'b':5}
a['g'] = 56
a['jj'] = num2
a['89'] = 'asdfg'
a['u'] =42
a['d'] = c1
a['11'] = 40
a['0'] = num1
print(a)
for key in a:
    print(key, a[key])

output

Tao
  • 41
  • 3
  • In Python 3.7 and newer, `dict` objects will always maintain insertion order -- this is now mandated by the spec. (Actually it's been this way since 3.6 in CPython, 3.7 just makes it official behavior of the language.) – Daniel Pryden Aug 14 '18 at 13:22
  • 1
    What version of Python are you using? `dict`s *were* unordered; CPython 3.6 ordered them as an implementation detail, and Python 3.7 made it official as part of the language spec. Note that the order is *insertion* order, not any particular ordering based on the key type. – chepner Aug 14 '18 at 13:23
  • Yes, it's the same. I'm sorry I didn't find that question before. – Tao Aug 14 '18 at 17:17

1 Answers1

4

dict retains insertion order from python 3.6 (due to internal implementation) and you can rely on the order from python 3.7

From Python 3.7 release notes

The insertion-order preservation nature of dict objects is now an official part of the Python language spec.

Sunitha
  • 11,777
  • 2
  • 20
  • 23