2

Possible Duplicate:
python looping seems to not follow sequence?
In what order does python display dictionary keys?

d = {'x': 9, 'y': 10, 'z': 20}
for key in d: 
    print d[key]

The above code give different outputs every time I run it. Not exactly different outputs, but output in different sequence. I executed the code multiple times using Aptana 3.

First Execution Gave: 10 9 20

Second Execution Gave: 20 10 9

I also executed the code in an online IDE http://labs.codecademy.com. There the output was always 10 9 20

I just wanted to know why is this. Ideally it should have printed 9 10 20 every time I execute the above code. Please Explain.

Community
  • 1
  • 1
Vzor Leet
  • 75
  • 1
  • 5

2 Answers2

3

A dictionary is a mapping of keys to values; it does not have an order.

You want a collections.OrderedDict:

collections.OrderedDict([('x', 9), ('y', 10), ('z', 20)])
Out[175]: OrderedDict([('x', 9), ('y', 10), ('z', 20)])

for key in Out[175]:
    print Out[175][key]

Note, however, that dictionary ordering is deterministic -- if you iterate over the same dictionary twice, you will get the same results.

Katriel
  • 120,462
  • 19
  • 136
  • 170
1

A dictionary is a collection that is not ordered. So in theory the order of the elements may change on each operation you perform on it. If you want the keys to be printed in order, you will have to sort them before printing(i.e. collect the keys and then sort them).

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176