SortedDict in Django
-
13-12-2019 - |
Question
I have a dictionary with a list of times I want to display in a template:
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"
})
I want to create a drop down in the template:
<select id="time_filter">
{% for key, value in time_filter.items %}
<option value="{{ key }}">{{ value }}</option>
{% endfor %}
</select>
But the elements in the drop down aren't coming through in the order defined in the dictionary. What am I missing?
Solution
Look here.
You are doing the "That does not work" thing, i.e. giving an unsorted dictionary as the input to the sorted dictionary.
You want
SortedDict([
(0, 'Eternity'),
(15, '15 minutes'),
# ...
(300, '300 minutes'),
])
OTHER TIPS
Consider using one of Python's many dictionary implementations that maintains the keys in sorted order. For example, the sortedcontainers module is pure-Python and fast-as-C implementations. It supports fast get/set/iter operations and keeps the keys sorted. There's also a performance comparison that benchmarks the implementation against several other popular choices.
You instantiate the SortedDict
with a "normal" dict
as an argument - your ordering is lost. You have to instantiate the SortedDict
with an iterable that preserves the ordering, e.g.:
SortedDict((
(0, "Eternity"),
(15, "15 Minutes"),
# ...
))
This answer may not exactly answer the question, you can use "dictsort" and "dictsortreversed" from django template tags to sort normal dict. So there is no need to use SortedDict.