Do dictionaries preserve order now?

user_ids = {“teraCoder”: 9018293, “proProgrammer”: 119238}
user_ids.update({“theLooper”: 138475, “stringQueen”: 85739})

When I run the above in Codeacademy the result is:
{‘stringQueen’: 85739, ‘theLooper’: 138475, ‘teraCoder’: 9018293, ‘proProgrammer’: 119238}

When I run the same code in my text editor, the result is:
{‘teraCoder’: 9018293, ‘proProgrammer’: 119238, ‘theLooper’: 138475, ‘stringQueen’: 85739}

Why the difference in the ordering?
The output of my text editor seems more rational to me since the additions are placed after the original content of the dictionary.

because only since python 3.6 dictionaries preserve order


whenever printing the dictionaries the sequence of key:value pair outputted are different.

user_ids = {"teraCoder": 9018293, "proProgrammer": 119238}
user_ids.update({"theLooper": 138475, "stringQueen": 85739})

Run 1 output:

#{'teraCoder': 9018293, 'proProgrammer': 119238, 'theLooper': 138475, 'stringQueen': 85739}

Run 2 output:

#{'proProgrammer': 119238, 'teraCoder': 9018293, 'theLooper': 138475, 'stringQueen': 85739}

why does this happen?


That is the nature of dictionaries. The price paid for lightning-fast (i.e., nearly constant-time) search of keys is that we cannot depend on their order within the dictionary. (This is the classic viewpoint, and may be slowly changing, i.e., in Python 3.6 and above, insertion order of dictionaries is preserved.) In general, you should avoid any code that depends upon the order of key:value pairs in a dictionary.

If you must make use of order, the OrderedDict subclass of the collections module is available.