can the sequence of entries in a dictionary be depended on?

Arnaud Delobelle arnodel at googlemail.com
Fri Nov 21 16:34:24 EST 2008


"Diez B. Roggisch" <deets at nospam.web.de> writes:

> Priya wrote:
>
>> Hi,
>> I'm writing a program where i iterate through the entries in a
>> dictionary using a for loop. This for-loop is enclosed by another loop
>> which traverses through a list and checks the relation between each
>> entry in the list and each entry in the dictionary.
>> while I know that dictionaries are 'unordered', I'd like to know if
>> the order of traversal will be the same each time the dictionary is
>> iterated through.
>> like if i have
>> dictionary={key1:"val1", key2:"val2",key3="val3"...}
>> for i in (1,10)
>>   for value in dictionary1:
>>      print value
>
> You are aware that the above code iterates over the *keys*, not the values?
>
>> am i assured that i always get the same sequence of outputs for any
>> two values of i?
>
> AFAIK the order is deterministic as long as you don't alter the dict between
> iterations. However, this is an implementation detail. Why don't you just
> do
>
> for key in sorted(dictionary.keys()):

That would work only if the keys are sortable, and would be wasteful
because you would need to sort the keys for each value of i.  A better
method may be to extract the keys before iterating over i:

keys = list(dictionary)

for i in 1, 10:
    for key in keys:
        ...

Then you know that keys will be iterated over in the same order.

-- 
Arnaud



More information about the Python-list mailing list