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

2024-06-17 09:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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?你知道吗

另外,我需要一个django模板。我只想在模板中(使用pyhaml),选项是字典:

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

Tags: django模板valueoneoptionsthreefoursorted
1条回答
网友
1楼 · 发布于 2024-06-17 09:37:27

标准Python字典是无序的。即使使用它,也无法以保持顺序的方式将值对存储在字典中。你知道吗

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

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

然后打印:

OrderedDict([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (6, 'six'), (8, 'eight'), (10, 'ten'), (12, 'Twelve'), (25, 'twentyfive')])

相关问题 更多 >