Bootstrap FreeKB - Jinja - Loop over a dictionary
Jinja - Loop over a dictionary

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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