What PEP controls the ordering of dict.values ()?
When you call dict.values (), the order of the returned items depends on the key value. This seems to be very consistent across 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 that specifically specifies the expected order of the items () and values () methods.
FYI, if this behavior is indeed the guaranteed behavior of the class I am working on, I could greatly simplify and speed up the class I am working on. On the other hand, if it's just a random and undocumented cPython feature, then it's probably best not to trust it.
a source to share
I assume PEP-3106 is as close as possible:
It follows from the spec that the order in which the items are returned by .keys (),. Values (), and .items () is (as in Python 2.x) because the order is all derived from a dict iterator (which presumably arbitrary, but stable until it changes). This can be expressed by the following invariant:
list(d.items()) == list(zip(d.keys(), d.values()))
a source to share
From http://docs.python.org/library/stdtypes.html :
Keys and values are listed in an arbitrary order, which is not random, varies in different Python implementations, and depends on the dictionaries, the history of insertion and deletion.
a source to share
"arbitrary" is not "random".
But this is the same as "undocumented". Since the dictionary is hash-based, you cannot - indeed - guarantee ordering based on the hash algorithm and the collisions that occur.
To guarantee the order, you use the function sorted
.
Or you can find a nice custom dictionary you want to use instead of dict.
a source to share