Why aren’t the values added to the dictionary in order?
Answer
In Python, a dictionary doesn’t add your items in the order you might expect. If we added 3 dishes, Burger, Salad, and Sammich, we’d expect them to appear in that order. But we’d be wrong!
There’s an advanced reason behind it, and like anything in programming, it’s because of efficiency. For now, just know that adding things to a dictionary does not add it in an order you’d expect, or necessarily at the end of the dictionary.
That’s the point. You should not rely on any order.
Python is free to do whatever it wants with that. (3.7 and later is not though, because it was added to the language specification that insertion order is kept)
Be careful:
You have to understand that dictionaries should not be used for ordering. You might lose performance.
List : We use a list if you have an ordered collection of items. These values can be CHANGED.
Dictionary : We use a dictionary when you have a set of UNIQUE keys that map to values to the keys
A dictionary is an unordered collection of key-value pairs. The function of a dictionary is not to order the values but to make associations.
The order for OrderedDict is based on insertion order. If you wanted to order it by something else you’d basically need to rebuild a new dictionary with that specific order.