dict
stores it's data in a hashtable data structure. So how does hashtable works?
On a nutshell: let's say the dict is initalized to 8 slots array-like object. When you add a new key-value pair to the dict, it hashes
the key using a function that returns the slot the key will reside. This isn't deterministic since the slot may be already taken; so you need to re-evaluate and look for another slot.
That's why the order you retrieve values from dict.values()
changes depend on the data in it. That's why it is called unordered.
For example, consider this simple dict:
>>> d = {'a': 1, 'aa': 2}
>>> d
{'a': 1, 'aa': 2}
>>> d = {'aa': 1, 'a': 2}
>>> d
{'aa': 1, 'a': 2}
If I change the order of the keys, it also appears different when I print the dict key-value pairs. But look what happens if I use different key
>>> d = {'b': 1, 'a': 2}
>>> d
{'a': 2, 'b': 1}
Althought I stated the 'b'
key first, it was allocated after 'a'
.
However, once the dict is set, it will always return the same order when called dict.items()
.