im actually not sure why that happens, nor have i ever had a situation where i needed them to stay in order..
al
x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> x
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': 1}
dicts sort their keys in alphabetical or numerical order... If order is very important to you... you might want to use 2 lists..
>>> x = ['five', 'one', 'four', 'two', 'three']
>>> y = [5, 1, 4, 2, 3]
>>> for i in y:
print 'key: %s value: %s' % (i, x[y.index(i)])
key: 5 value: five
key: 1 value: one
key: 4 value: four
key: 2 value: two
key: 3 value: three
>>>
Wish i had a better anwser for you... I just have never had an issue where order was important :(
lukerobi
Junior Poster in Training
50 posts since Sep 2009
Reputation Points: 14
Solved Threads: 16
just an afterthought.... You could keep your dict and just keep a list to remember it's order...
>>> x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> y = ['two', 'one', 'five', 'three', 'four']
>>> for i in y:
print 'key: %s value: %s' % (i, x[i])
key: two value: 2
key: one value: 1
key: five value: 5
key: three value: 3
key: four value: 4
>>>
lukerobi
Junior Poster in Training
50 posts since Sep 2009
Reputation Points: 14
Solved Threads: 16
In python 3 you can do
from collections import OrderedDict
which gives you a class which remembers insertion order.
For older pythons, you can try to use a class found on the web like http://code.activestate.com/recipes/107747/ .
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
Just a note: dictionaries keep their keys in a hash order to speed up searches. If you want to keep the entry order you can just use a list of (key, value) tuples which you can also sort if need be.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417