6

I feel like I'm missing something obvious here!

seq = {'a': ['1'], 'aa': ['2'], 'aaa': ['3'], 'aaaa': ['4'], 'aaaaa': ['5']}
for s in seq:
    print(s)

outputs:

a
aa
aaaa
aaaaa
aaa

Whereas surely it should output:

a
aa
aaa
aaaa
aaaaa

What's going wrong here?

martineau
  • 119,623
  • 25
  • 170
  • 301
significance
  • 4,797
  • 8
  • 38
  • 57
  • 3
    duplicated http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value and http://stackoverflow.com/questions/575819/sorting-a-dictionary-in-python – jargalan Nov 08 '10 at 11:17

3 Answers3

15

Dictionaries are not ordered. If you need to rely on the ordering, you need an OrderedDict - there's one in the collections module in Python 2.7, or you can use one of the many recipes around.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    You also may want to point out that an OrderedDict is not a sorted dictionary. An OrderedDict merely preserves the order in which keys were added. – Steven Rumbalski Nov 08 '10 at 14:53
5

Standard Python dictionaries are not ordered: there is no guarantee on which order the keys will be returned.

If you want your keys returned in the order in which you create keys you can use an OrderedDict from collections.

Alternatively, if you want your output sorted on the values of the keys the following would do:

for s in sorted(seq):
    print s
David Webb
  • 190,537
  • 57
  • 313
  • 299
1

why you don't do (dictionary are not ordered):

for s in range(5):
    print 'a'*s

Edit : ok as you which :)

the thing is in the expression : 'a'*s which mean create a new string which contain s time 'a'.

in the python interpreter you can play with it (isn't python wonderful :) )

>>> print 'a'*2
aa
>>> print 'a'*3
aaa 

PS: if you're new to python i will suggest that you use ipython if you don't use it yet.

mouad
  • 67,571
  • 18
  • 114
  • 106