[Django]-How to iterate over nested dictionaries in django templates

41👍

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

8👍

as rolling stone says thats the way to iterate over dictionaries in templates, i would only change the key, value keywords for different keywords in every iteration like this:

{% 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 %}

just for the sake of clarity 🙂

And if you want to line up your values i would suggest you use another data structure where you can sort by date, for example a something like this:

{ 'oranges' : [(date1, value1), (date2,value2)] ...}

Try to do the least possible operations in your templates, so dont do a sort or nested if’s if you dont have to

👤Hassek

1👍

Really old question, but I will add my 1.5c.

This is a good use case of the regroup tag (https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#regroup) and a bit of data refactoring:

  1. Have your data as a simple list of data points:

    harvest_data = [
        {'fruits': 'apples', 'date': '2011-07-23', 'total': 100, 'good': 80},
        # ...
    ]
    
  2. In your template, group by the chosen dimension(s):

    {% regroup harvest_data by fruits as data_by_fruits %}
    {% for data in data_by_fruits %}
        <h1>{{ data.grouper }}</h1>   # 'apples'
        {% regroup data.list by date as data_by_fruits_date %}
        {% for data_1 in data_by_fruits_date %}
            <h2>{{ data_1.grouper }}</h2>    # '2011-07-23'
            {% for datapoint in data_1.list %}
                total: {{ datapoint.total }} <br/>
                good: {{ datapoint.good }} <br/>
            {% endfor %}
        {% endfor %}
    {% endfor %}
    

Leave a comment