Jinja - Sort a Dictionary

by
Jeremy Canfield |
Updated: August 25 2024
| Jinja articles
sort is a Jinja filter that can be used to:
- sort a dictionary (this article)
- sort a list
Take for example the following.
{% set dict={"foo": "hello", "bar": "world"} %}
<br /><br />
Original Dictionary:
{{ dict }}
<br /><br />
Unsorted Dictionary:
<br />
{% for key, value in dict.items() %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
<br /><br />
Sorted Dictionary:
<br />
{% for key, value in dict.items() | sort %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
<br /><br />
Sorted Dictionary in Reverse Order:
<br />
{% for key, value in dict.items() | sort(reverse=true) %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
Something like this should be returned. Notice that with the unsorted dictionary, the "foo" key precedes the "bar" not, thus not sorted alphabetically. With the sorted dictionary, the "bar" key precedes the "foo" key, thus the output is sorted alphabetically.
Original Dictionary: {'foo': 'hello', 'bar': 'world'}
Unsorted Dictionary:
key = foo
value = hello
key = bar
value = world
Sorted Dictionary:
key = bar
value = world
key = foo
value = hello
Sorted Dictionary in Reverse Order:
key = foo
value = hello
key = bar
value = world
And here is another example that uses attribute to sort a list that contains key/value pairs.
{% set my_list = [{'fruit': 'orange', 'veggy': 'pepper'}, {'veggy': 'tomato', 'fruit': 'apple'}] %}
Original my_list:
{{ my_list }}
<br /><br />
Unsorted:
<br />
{% for dict in my_list %}
{% for key, value in dict.items() %}
{% if key == "fruit" %}
value = {{ value }}
<br />
{% endif %}
{% endfor %}
{% endfor %}
<br />
Sorted:
<br />
{% for dict in my_list | sort(attribute="fruit") %}
{% for key, value in dict.items() %}
{% if key == "fruit" %}
value = {{ value }}
<br />
{% endif %}
{% endfor %}
{% endfor %}
Something like this should be returned. Looping through my_list, the output is sorted based on the value of the "fruit" key in each dictionary.
Original my_list: [{'fruit': 'orange', 'veggy': 'pepper'}, {'veggy': 'tomato', 'fruit': 'apple'}]
Unsorted:
value = orange
value = apple
Sorted:
value = apple
value = orange
In this example, my_list will be sorted on the "fruit" key in reverse order.
{% for dict in my_list | sort(attribute="fruit", reverse=true) %}
You can chain together multiple sorts.
{% for dict in my_list | sort(attribute="fruit") | sort(attribute="veggy") %}
Did you find this article helpful?
If so, consider buying me a coffee over at