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])
dictobjects 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.)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.