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

Diez B. Roggisch deets at nospam.web.de
Fri Nov 21 13:40:00 EST 2008


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()):
   ...

Diez



More information about the Python-list mailing list