Dictionary sorting
Tim Chase
python.list at tim.thechases.com
Thu Nov 3 19:01:38 EDT 2011
On 11/03/11 16:36, Terry Reedy wrote:
> > Is there a way to not sort them and leave the order as is?
>
> CPython iterates (and prints) dict items in their arbitrary internal
> hash table order, which depends on the number and entry order of the
> items. It is a bug to depend on that arbitrary order in any way.
Does this "never trust it" hold even for two consecutive
iterations over an unchanged dict? I didn't see anything in the
docs[1] to make such a claim, but at least from my experience,
one can reliably assert
d = {}
randomly_populate(d)
list1 = list(d.iterkeys())
list2 = list(d.iterkeys())
assert list1 == list2
I understand all bets are off if one adds/removes (or maybe
changes the values) of the dict between iterations, but I didn't
know if what I saw was merely an implementation detail that
shouldn't be counted on.
-tkc
[1]
http://docs.python.org/library/stdtypes.html#mapping-types-dict
More information about the Python-list
mailing list