iterate over a dictionary inside a django template Apr
27
1
0

The official Django documents how to iterate over a dictionary inside a for loop, but I sometimes forget. I'll attempt to do something like this:

{% for key, value in data %}
    {{ key }}: {{ value }}
{% endfor %}

but will fail miserably. The key to extracting a dictionary inside django templates is the items dictionary function, which "Return a copy of the dictionary’s list of (key, value) pairs".

This allows us to loop through the dictionary using items like so:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}
Bookmark and Share
blog comments powered by Disqus