Dictionary sorting

Hrvoje Niksic hniksic at xemacs.org
Fri Nov 4 06:20:06 EDT 2011


Ben Finney <ben+python at benfinney.id.au> writes:

> Tim Chase <python.list at tim.thechases.com> writes:
>
>> On 11/03/11 16:36, Terry Reedy wrote:
>> > 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,
>
> Exactly.

This is false.  The docs say:

    If items(), keys(), values(), iteritems(), iterkeys(), and
    itervalues() are called with no intervening modifications to the
    dictionary, the lists will directly correspond. This allows the
    creation of (value, key) pairs using zip(): pairs = zip(d.values(),
    d.keys()).

(http://docs.python.org/library/stdtypes.html#mapping-types-dict)

> The order of retrieval is entirely up to the implementation.

This part is still true, but the order won't change behind your back if
you're not touching the dict.



More information about the Python-list mailing list