Skip to main content
 首页 » 编程设计

python之Django 中的 SortedDict

2025年05月04日19sxdcgaq8080

我有一本字典,里面有我想在模板中显示的时间列表:

from django.utils.datastructures import SortedDict 
 
time_filter = SortedDict({ 
    0 : "Eternity", 
    15 : "15 Minutes", 
    30 : "30 Minutes", 
    45 : "45 Minutes", 
    60 : "1 Hour", 
    90 : "1.5 Hours", 
    120 : "2 Hours", 
    150 : "2.5 Hours", 
    180 : "3 Hours", 
    210 : "3.5 Hours", 
    240 : "4 Hours", 
    270 : "4.5 Hours", 
    300 : "5 Hours" 
}) 

我想在模板中创建一个下拉列表:

<select id="time_filter"> 
    {% for key, value in time_filter.items %} 
        <option value="{{ key }}">{{ value }}</option> 
    {% endfor %} 
</select> 

但是下拉列表中的元素并没有按照字典中定义的顺序出现。我错过了什么?

请您参考如下方法:

看here .

您正在做“那行不通”的事情,即将未排序字典作为已排序字典的输入。

你想要

SortedDict([ 
    (0, 'Eternity'), 
    (15, '15 minutes'), 
    # ... 
    (300, '300 minutes'), 
])