Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping seems to not follow sequence

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?

like image 427
significance Avatar asked Nov 08 '10 11:11

significance


2 Answers

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.

like image 188
Daniel Roseman Avatar answered Oct 05 '22 07:10

Daniel Roseman


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
like image 44
Dave Webb Avatar answered Oct 05 '22 08:10

Dave Webb