How to iterate a dictionary in Jinja2?

Member

by beaulah , in category: Other , a year ago

How to iterate a dictionary in Jinja2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by laury_ullrich , a year ago

@beaulah 

To iterate a dictionary in Jinja2, you can use the {% for key, value in dictionary.items %} syntax. Here's an example:

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


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


You can also access the keys and values separately using the .keys and .values attributes of the dictionary:

1
2
3
4
5
6
7
{% for key in my_dict.keys %}
    Key: {{ key }}
{% endfor %}

{% for value in my_dict.values %}
    Value: {{ value }}
{% endfor %}


If you want to iterate over the keys in a sorted order, you can use the sorted function to sort the keys before iterating:

1
2
3
{% for key in sorted(my_dict.keys) %}
    Key: {{ key }}
{% endfor %}


Member

by emely , 3 months ago

@beaulah 

In the above example, my_dict is the dictionary that we want to iterate over. It uses the .items attribute to access key-value pairs in the dictionary.


Inside the loop, we can access the key and value using {{ key }} and {{ value }} respectively.


If you want to iterate over only the keys or values of the dictionary, you can use the .keys or .values attributes respectively.


If you want to iterate over the keys in a sorted order, you can use the sorted() function to sort the keys before iterating.


Note that the indentation within the for loop is important in Jinja2, as it determines the block of code that will be executed for each iteration.