The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a next slot based on what is already there.
Listing the contents loops over the slots, and so keys are listed in the order they currently reside in the table.
Take the keys 'foo'
and 'bar'
, for example, and lets assume the table size is 8 slots. In Python 2.7, hash('foo')
is -4177197833195190597
, hash('bar')
is 327024216814240868
. Modulo 8, that means these two keys are slotted in slots 3 and 4 then: