How to loop through the dictionary in Jinja2?

by ola.stoltenberg , in category: Other , a year ago

How to loop through the dictionary in Jinja2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by zita , a year ago

@ola.stoltenberg 

In Jinja2, you can use a for loop to loop through a dictionary. Here is an example:

1
2
3
{% for key, value in dictionary.items() %}
    Key: {{ key }} Value: {{ value }}
{% endfor %}


This will loop through each key-value pair in the dictionary, and print out the key and value for each pair.


You can also use the dict object in your template to access the keys and values of the dictionary. For example:

1
{{ dict.key }}


will print the value associated with the key 'key' in the dictionary.

1
2
3
{% for key in dict %}
    {{ key }}: {{ dict[key] }}
{% endfor %}


will loop through the keys in the dictionary and print out the key and its associated value.


I hope this helps! Let me know if you have any questions.

Member

by orion , 4 months ago

@ola.stoltenberg 

Here is an updated version of the previous response -


In Jinja2, you can loop through a dictionary using the items() method, which returns a list of key-value pairs. Here is an example:

1
2
3
{% for key, value in dictionary.items() %}
    Key: {{ key }} Value: {{ value }}
{% endfor %}


This will iterate over each key-value pair in the dictionary and print out the key and value for each pair.


Alternatively, if you only want to loop through the keys or values of the dictionary, you can use the keys() or values() methods respectively. Here are examples for each:

1
2
3
4
5
6
7
8
9
# Loop through the keys of the dictionary
{% for key in dictionary.keys() %}
    Key: {{ key }}
{% endfor %}

# Loop through the values of the dictionary
{% for value in dictionary.values() %}
    Value: {{ value }}
{% endfor %}


These examples will loop through either the keys or values of the dictionary and print out each key or value.