python:为什么排序不能正确排序整数?

时间:2015-10-07 19:49:58

标签: python sorting dictionary

a = {1: "one", 2:"two", 4:"four", 3:"three", 25:"twentyfive", 10:"ten", 8:"eight", 6: "six", 12:"Twelve"}
sorted(a)

结果:

{1: 'one', 2: 'two', 3: 'three', 4: 'four', 6: 'six', 8: 'eight', 25: 'twentyfive', 10: 'ten', 12: 'Twelve'}

为什么25在10和12之前出现?

PS。我需要在django模板中使用它。我只想在模板中(使用pyhaml),选项是字典:

                %div.options
                  Options:
                    - for key, value in options.items
                      //print the value 

1 个答案:

答案 0 :(得分:0)

标准Python词典是无序的。即使你这样做,你也无法以保持排序的方式将值对存储在字典中。

如果您想按字符键对字典进行排序,可以使用OrderedDict,如之前在StackOverflow中所建议的那样:

word = input("Please enter the encrypted word: ")
message = ""
times = 0
for i in range(58):
    message = ""
    for ch in word:
        val=ord(ch)
        val = (val-times)
        if val > ord('z'):
            val = ord('a') + (val - ord('z')-1)
        message +=chr(val)   
    print("Here is your encrypted message: ", message)
    times += 1

然后打印:

import collections
a = {1: "one", 2:"two", 4:"four", 3:"three", 25:"twentyfive", 10:"ten", 8:"eight", 6: "six", 12:"Twelve"}
sorted_a = collections.OrderedDict(sorted(a.items()))
print sorted_a