How to iterate over nested dictionaries in django templates

Since you’re familiar with python, the following is logically how you would want to iterate through your dictionary in a Django template:

for key,value in harvest_data.items():
...     print key
...     for key2,value2 in value.items():
...         print key2
...         for key3,value3 in value2.items():
...             print "%s:%s"%(key3,value3)

In your template, this translates as follows:

{% for key, value in harvest_data.items %}
    {{ key }} <br>
    {% for key2,value2 in value.items %}
        {{ key2 }} <br>
        {% for key3, value3 in value2.items %}
            {{ key3 }}:{{ value3 }} <br>
        {% endfor %}
    {% endfor %}
{% endfor %}

The Django docs actually briefly include an example of how to iterate through dictionaries when describing how the for template tag works:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

Leave a Comment