Django中的SortedDict

Ed.*_*Ed. 1 python django ordereddictionary django-templates sorteddictionary

我有一个字典,其中包含我想要在模板中显示的列表:

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"
})
Run Code Online (Sandbox Code Playgroud)

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

<select id="time_filter">
    {% for key, value in time_filter.items %}
        <option value="{{ key }}">{{ value }}</option>
    {% endfor %}
</select>
Run Code Online (Sandbox Code Playgroud)

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

sim*_*lmx 5

你看这里.

你正在做"那不行"的事情,给一个未排序的字典作为排序字典的输入.

你要

SortedDict([
    (0, 'Eternity'),
    (15, '15 minutes'),
    # ...
    (300, '300 minutes'),
])
Run Code Online (Sandbox Code Playgroud)


Gra*_*ntJ 5

考虑使用Python的许多字典实现之一,按照排序顺序维护密钥.例如,sortedcontainers模块是纯Python和快速实现的C实现.它支持快速get/set/iter操作并保持按键排序.还有一个性能比较,它将实现与其他几个流行的选择进行了基准测试.