Previous Page Next Page

Sorting Dictionaries

The dictsort filter is a useful tool when you want to display the data from a template in a different order. The dictsort filter can be applied to a list of dictionaries. It accepts a key name as the only argument. The filter renders a sorted list based on the key given in the argument.

By the Way

If you need to sort the list of dictionaries in reverse order, you can use the dictsortreversed filter in the same way that you use dictsort. The only difference is that the dictionaries are sorted in reverse order.


To show an example of using a dictsort filter table, the following template code renders a table of flight data that comes from a list of flights stored in dictionaries. The sample code sorts the list using the dictsort:'departure' filter to sort the list by the departure key before rendering the table.

<h1>Departure Table</h1>
<table border="1" cellpadding="2">
<tr bgcolor="dddddd">
    <td>Departure</td>
    <td>Arrival</td>
    <td>Flight Number</td>
</tr>
{% for f in flights|dictsort:"departure" %}
<tr>
    <td>{{ f.depeparture }}</td>
    <td>{{ f.arrival }}</td>
    <td>{{ f.flightnum }}</td>
</tr>
{% endfor %}
</table>

As another example, use the same code, but change the <h1> text to "Arrival Table," and change the dictsort argument for tag to the following code:

{% for f in flights|dictsort:"arrival" %}

By doing this, you can render another table with the flights sorted by the arrival key. The result is a web page similar to the one shown in Figure 9.6.

Figure 9.6. Two tables generated with the same date in a different sort order using the dictsort filter.


Previous Page Next Page