11

i need help for this case :

m={}
m[1]=1
m[333]=333
m[2]=2

# Result:
{1: 1, 2: 2, 333: 333}

so even when i didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fix the order. but that's not what i want, i just simply want to print and get output order just like the order when i input the data. Is there any good explanation and is there any solution ?

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
andio
  • 1,574
  • 9
  • 26
  • 45

3 Answers3

23

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.OrderedDict in 2.7 and 3.1+, there is also standalone module for 2.4-2.6.

wRAR
  • 25,009
  • 4
  • 84
  • 97
  • @wRAR : done ;-) .sorry i'm new to this forum, i've just found out the way this forum works (specially about rating and accept things). sorry and thanx a lot. – andio May 08 '12 at 05:02
2

Items stored in a dictionary do not have any inherent order. The order they are printed out is entirely down to the hash values for each of the keys and the other items in the dictionary.

Will
  • 4,585
  • 1
  • 26
  • 48
0

Long time after this questions was posted, but just for those who land on this page, since 3.6? dictionaries preserve the order that items are added in.

Mark Kortink
  • 1,770
  • 4
  • 21
  • 36