Jinja - Loop over a dictionary

by
Jeremy Canfield |
Updated: January 16 2024
| Jinja articles
Here is a basic example of how to loop over a list of values in Jinja.
{% set dict={"foo": "hello", "bar": "world"} %}
Original Dict:
{{ dict }}
<br /><br />
{% for key, value in dict.items() %}
key = {{ key }}
value = {{ value }}
{% endfor %}
Something like this should be returned.
Original Dict: {'foo': 'hello', 'bar': 'world'}
key = foo
value = hello
key = bar
value = world
Or like this, if the dictionary is in a list, using items().
{% set my_list = [{'fruit': 'apple', 'veggy': 'pepper'}, {'veggy': 'tomato', 'fruit': 'orange'}] %}
Original my_list:
{{ my_list }}
<br /><br />
Unsorted:
<br /><br />
{% for dict in my_list %}
{% for key, value in dict.items() %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
{% endfor %}
<br /><br />
Sorted:
<br /><br />
{% for dict in my_list %}
{% for key, value in dict.items() | sort %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
{% endfor %}
Something like this should be returned. Notice with the unsorted list, the keys are not sorted alphabetically (veggy precedes fruit in the second dictionary). With the sorted list, the keys are sorted alphabetically (fruit precedes veggy in the second dictionary).
Original my_list: [{'fruit': 'apple', 'veggy': 'pepper'}, {'veggy': 'tomato', 'fruit': 'orange'}]
Unsorted:
key = fruit
value = apple
key = veggy
value = pepper
key = veggy
value = tomato
key = fruit
value = orange
Sorted:
key = fruit
value = apple
key = veggy
value = pepper
key = fruit
value = orange
key = veggy
value = tomato
Or like this, using dictsort.
{% set my_list = [{'fruit': 'apple', 'veggy': 'pepper'}, {'fruit': 'orange', 'veggy': 'tomato'}] %}
Original my_list:
{{ my_list }}
<br /><br />
{% for dict in my_list %}
{% for key, value in dict | dictsort %}
key = {{ key }}
<br />
value = {{ value }}
<br />
{% endfor %}
{% endfor %}
Did you find this article helpful?
If so, consider buying me a coffee over at