views:

138

answers:

3

When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict simply states that the ordering is "arbitrary".

I remember reading somewhere that there is actually a PEP which specifically states the expected ordering of the items() and values() methods.

FYI, if this behavior is indeed a guaranteed behavior of a class I am working on I could greatly simplify and speed up a class I am working on. On the other hand if this is merely an accidental and undocumented feature of cPython then it's probably best not to trust it.

+6  A: 

From http://docs.python.org/library/stdtypes.html:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

Benji York
+2  A: 

"arbitrary" is not the same as "accidental".

But it is the same as "undocumented". Since the dictionary is based on hashes, you can't -- really -- guarantee ordering based on the hashing algorithm and collisions which occur.

To guarantee an order, you use the sorted function.

Or you can find a good ordered dictionary implementation that you want to use instead of a dict.

S.Lott
+5  A: 

I suppose PEP-3106 is as close as it gets:

The specification implies that the order in which items are returned by .keys(), .values() and .items() is the same (just as it was in Python 2.x), because the order is all derived from the dict iterator (which is presumably arbitrary but stable as long as a dict isn't modified). This can be expressed by the following invariant:

list(d.items()) == list(zip(d.keys(), d.values()))

SilentGhost
Note that the order will be consistent for a given dict (until that dict is modified) on a given Python version, on a given platform. So you can rely on a given dict staying ordered the same way within a single instance of your running code, but not beyond that.Of course, it's better practice to never rely on anything related to the ordering of a dict.
Carl Meyer