Reputation:
We know that regular Python dictionaries are unordered, but what about the case when the keys are the set of natural numbers? The hash
function seems to be an identity function when the domain is the set of natural numbers, and iterating over something like x = {0:'a', 1:'b', 2:'c'}
seems to yield the natural order of the keys, aka 0, 1, 2..
So can this behavior be relied on?
(Yes I know about OrderedDict)
EDIT:
Here's my specific usage, or at least this captures the spirit of what I'm looking at.
x = dict((a, chr(a)) for a in range(10))
for i in x:
print i
This seems to preserve order.
Upvotes: 1
Views: 125
Reputation: 179602
Nope. Never, ever, ever rely on the order of the dictionary keys. An illustrative example:
>>> {0: 1, 8: 2}
{0: 1, 8: 2}
>>> {8: 1, 0: 2}
{8: 1, 0: 2}
This happens because a dictionary starts off with 8 buckets. Thus, 0 and 8 end up in the same bucket, which will cause an immediate collision. The order depends on which is inserted first. (But don't rely on that either: that initial size isn't a guarantee!)
You are correct, however, that the hash
of int
s (in Python 2.x) is the identity function (with the sole exception of -1
, which is mapped to -2
to avoid collision with the usual "error return" value). However, the distinction between int
and long
is quite subtle sometimes, and long
s use a different hashing algorithm (because they can be arbitrarily large).
Upvotes: 6
Reputation: 304393
No. The order also depends on the order the keys are inserted.
Upvotes: 0
Reputation: 59556
No, you cannot rely on that behaviour. It is an implementation detail which can change from one version of Python to the next or even from one system to the next.
That being said, it is unlikely to change soon.
Upvotes: 0