Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...