Django Template – display dictionary in a sorted order

I was running Django 1.2 and after upgrading to Django 1.8, the list of accounts on a dashboard didn’t show up in Alphabetical order. I read through this article on Stack Overflow and found this solution. Additional reading material in the Django Tutorial.

Create a custom filter within any existing app. To create a new custom filter for the first time, create a PyDev package under any of the apps that is listed in the installed apps for Django. Create a file called and add the following code to it:

from django import template
from django.utils.datastructures import SortedDict

register = template.Library()

def listsort(value):
    if isinstance(value, dict):
        new_dict = SortedDict()
        key_list = sorted(value.keys())
        for key in key_list:
            new_dict[key] = value[key]
        return new_dict
    elif isinstance(value, list):
        return sorted(value)
        return value
    listsort.is_safe = True

Within the template, access the key and values of the dictionary as follows:

{% for anchor, accounts in result_set.items|sort %}
  <p name="{{anchor}}"><a>{{anchor}}</a> <a href="#" onclick="scrollToLetter('top'); return false;" class="help">(top)</a></p>
  {% for account in accounts %}
    {% with account.company_name as encoded_name %}
    <li><a href="{%url 'getQuotes' encoded_name%}" data-name="{{account}}">{{account}}</a></li>
    {% endwith %}
  {% endfor %}
{% endfor %}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s