How to render an ordered dictionary in django templates?


Question

I'm trying to learning django templates but it's not easy.
I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way:

return render_to_response('results.html', {'data': results_dict})

Now my problem is that in my template I need to display the names in alphabetical (or ASCIIbetical) order with the relatives values.
Actually in my template I have:

<table>
{% for key, value in data.items %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
</table>

How can I render the data in sorted way? Many thanks.

1
39
3/10/2011 8:43:53 AM

Accepted Answer

In views.py (Python2):

return render_to_response('results.html',
    {'data': sorted(results_dict.iteritems())})

Or in views.py (Python3):

return render_to_response('results.html',
    {'data': sorted(results_dict.items())})

In template file:

{% for key, value in data.items() %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
{% endfor %}
60
5/17/2018 11:47:19 PM

Although changing the code in the view is preferable, you could also use the dictsort template tag:

https://docs.djangoproject.com/es/1.9/ref/templates/builtins/#std:templatefilter-dictsort

<table>
{% for key, value in data.items|dictsort:"0.lower" %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
</table>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon