Reputation: 1435
I am familiar with the fact that in Python (<3.6) the order of a dict cannot be predicted at initialisation, for example:
d = {'B' : 2, 'A' : 1, 'C' : 3}
creates this dictionary on my computer:
{'A': 1, 'C': 3, 'B': 2}
My question is whether the order will stay unpredictable after initialisation, or that once it is written to memory, it is fixed. Why is that (not) the case? (This assumes that the dictionary is not written to after init)
In other words, if I run
print(d.keys())
print(d.values())
consecutively will the 2 results always match up?
Upvotes: 1
Views: 150
Reputation: 7241
Those two values will always matchup.
The reason being is that the dict
object is really a hashmap
data structure, and once it has been initialized, it is now created in memory (RAM) of your computer. Therefore, unless something changes that memory block (i.e., your code, your compiler, or some unforeseen circumstance like a memory-based infection), your reference to that object in memory, i.e., your dict
object, will never change.
Upvotes: 3