Based on what I know, you can’t assume that a data structure (such as dictionary) will save the values in it on the same order as what you have initialized it.
For example:
d = {1:10,2:20,3:30}
when you print it inside a for loop, the result could be:
{2:20,1:10,3:30}
Why it happens – why the dictionary (or the other data structure) won’t keep the values in a specific order?
Is it true only for dictionaries?
Among the Python builtin types, it’s true for dictionaries and sets. Lists and tuples preserve order. There is
collections.OrderedDictfor an ordered version of a dictionary. For other types (e.g., ones from libraries that aren’t built into Python), you just have to read the documentation. There’s no general rule for what a “data structure” does in Python. You have to look at the documentation of each type to understand what behavior it does or doesn’t define.Python does define the notion of “sequence”, which is defined to have order (lists and tuples are sequences). A dictionary is a “mapping”, which needn’t have order. (See the Python glossary and the collections module for more info.)
As to why, it’s just how dictionaries were implemented. Basically they can be faster if they don’t have to keep track of order, and in many cases you don’t care about the order, so they were implemented as unordered collections for efficiency.