保留原始的字典顺序而不是随机的?

时间:2014-04-29 16:59:44

标签: python python-2.7 dictionary

如果您查看以下代码:

examples = {"Main 1": "blabla", "Main 2": "test", "Main 3": "ya", "Main 4": "ha", "Main 5": "no", "Main 6": "blabla", "Main 7": "test", "Main 8": "ya", "Main 9": "ha", "Main 10": "no", "Main 11": "blabla", "Main 12": "test", "Main 13": "ya", "Main 14": "ha", "Main 15": "no", "Main 16": "boo", "Main 17": "blabla", "Main 18": "test", "Main 19": "ya", "Main 20": "ha", "Main None": "None",}

for example in examples.keys():
    print example

它打印以下内容:

Main 1
Main 14
Main 3
Main 2
Main 5
Main 4
Main 7
Main 6
Main 9
Main 8
Main None
Main 12
Main 19
Main 17
Main 18
Main 16
Main 13
Main 15
Main 20
Main 11
Main 10

如何使它保持dict顺序,使其成为1,2,3,4,5,6,7 ...等等

1 个答案:

答案 0 :(得分:1)

普通词典由hash table构成,不保留排序。请改用标准库OrderedDict模块中的collections