Django | sort dict in template
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.
a custom template filter will do the trick.
from django import template
register = template.Library()
def dict_get(value, arg):
#custom template tag used like so:
#{{dictionary|dict_get:var}}
#where dictionary is duh a dictionary and var is a variable representing
#one of it's keys
return value[arg]
register.filter('dict_get',dict_get)
more on custom template filters: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags
in your example you'd do:
{% for employee, dependents in company_dict|company %}