Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django | sort dict in template

Tags:

python

django

I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.

{% for company in companies %}
    {% for employee, dependents in company_dict.company.items %}
    {% endfor %}
{% endfor %}

(Just made up the example...) The part that doesn't work is the "company_dict.company.items" part. I need the "company" to be the value of company. Right now the company prat is looking for a key named "company" not the value of "company" from the loop above.

I'm doing a bit of processing to put the dictionary of dictionaries together. Changing the layout of the data isn't really an option. I figure the right approach is to write up a template tag, just wanted to know if there was a built-in way I missed.

like image 926
johannix Avatar asked Jan 08 '10 00:01

johannix


1 Answers

create a custom filter, which is like this:

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

register = template.Library()

@register.filter(name='sort')
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)
    else:
        return value
    listsort.is_safe = True

then in your template you shall call it using:

{% for key, value in companies.items|sort %}
      {{ key }} {{ value }}
{% endfor %}

You will be able to get the sorted dict by Key.

like image 68
Turikumwe Avatar answered Oct 14 '22 05:10

Turikumwe