Dictionaries are not in random order. They are in arbitrary order. In this case, you got lucky and they were sorted. Tomorrow, they might not be. If you need randomness, use random
. If you need sorted order, use sorted()
. As @BenjaminWohlwend mentions in the comments, you can use collections.OrderedDict
to keep track of insertion order.
In this case, I would guess the dictionary is doing some sort of small-integer-key optimization, acting like an array (e.g. hash(1) == 1
). This is not a guaranteed behavior and might work differently on other Python implementations.