dictsort Filter

Data Structure

Argument: key (required)

Documentation

Sorts a list of dictionaries by key.

Variable

foods = [
    {'name': 'Apple', 'category': 'Fruit'},
    {'name': 'Banana', 'category': 'Fruit'},
    {'name': 'Corn', 'category': 'Vegetable'},
    {'name': 'Grape', 'category': 'Fruit'},
    {'name': 'Hamburger', 'category': 'Meat'},
    {'name': 'Pepper', 'category': 'Vegetable'},
]

Template

<ol>
  {% for food in foods|dictsort:'category' %}
    <li>{{ food.name }}, {{ food.category }} </li>
  {% endfor %}
</ol>

Result

<ol>
    <li>Apple, Fruit </li>
    <li>Banana, Fruit </li>
    <li>Grape, Fruit </li>
    <li>Hamburger, Meat </li>
    <li>Corn, Vegetable </li>
    <li>Pepper, Vegetable </li>
</ol>

Notice that the list is sorted by category.

dictsort can also be used to sort lists of other sequences using the index of the item you wish to sort by as the argument.


Did we get something wrong? Is there a use case for the dictsort filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Sept. 16, 2020, 7:34 p.m. EST