Bootstrap FreeKB - Jinja - Sort a Dictionary
Jinja - Sort a Dictionary

Updated:   |  Jinja articles

sort is a Jinja filter that can be used to:

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 the list.

{% 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

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 23b5a9 in the box below so that we can be sure you are a human.