3

Possible Duplicate:
Why is python ordering my dictionary like so?

Why iteration on this dict

d = {'tors':None,
     'head':None,
     'armr':None,
     'arml':None,
     'legl':None,     
     'legr':None}

for k in d.keys():
    print k

will output keys in different order:

head
legl
armr
arml
tors
legr
Community
  • 1
  • 1
avalanchy
  • 814
  • 1
  • 11
  • 19

2 Answers2

6

In python dict is implemented as hash map and nobody can't guarantee keys order. From documentation

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

If you need to keep ordering, use collections.OrderedDict instead.

Alexey Kachayev
  • 6,106
  • 27
  • 24
  • Thank you. But another question. Maybe will suggest different struct to keep values? I access like this: eg `self.body[key]['pos']`. – avalanchy Oct 25 '12 at 11:22
1

This should do the job:

import collections

ordered_d = collections.OrderedDict([('banana', 3),('apple',4),('pear', 1),('orange', 2)])
for k in ordered_d.keys():
    print k

with the result:

banana
apple
pear
orange
doru
  • 9,022
  • 2
  • 33
  • 43