Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render an ordered dictionary in django templates?

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.

like image 387
green69 Avatar asked Mar 09 '11 18:03

green69


1 Answers

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 %} 
like image 140
Yuji 'Tomita' Tomita Avatar answered Sep 28 '22 23:09

Yuji 'Tomita' Tomita