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

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.) Commented Aug 14, 2018 at 13:22
  • 1
    What version of Python are you using? dicts 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. Commented Aug 14, 2018 at 13:23
  • Yes, it's the same. I'm sorry I didn't find that question before. Commented Aug 14, 2018 at 17:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Didn't know there was a change recently, could you link some docs/release notes stating this?
Yes, it's the answer what I need. Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.