Python Dictionary Iteration Order Is Unexpectedly Sorted. Why?
Solution 1:
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.
Solution 2:
The order is not random, it's arbitrary. What that means is that you can't depend on it iterating in any particular order. It may sometimes happen to be in sorted order, but you can't assume it will be.
Post a Comment for "Python Dictionary Iteration Order Is Unexpectedly Sorted. Why?"