All Іѕ Vаиітy
All Іѕ Vаиітy

Reputation: 26462

How do I properly loop through this context dictionary in Django?

I'm trying to loop through a nested context dictionary where I'm missing something, The dictionary I'm working on is,

output =
    {
        'results': {

            'result2': {

                'name': 'Alex',
                'roll': 5,
                'phone': 'not provided',
                'email': '[email protected]',
                'grade': 8,
            },

            'result0': {

                'name': 'John',
                'roll': 23,
                'phone': 'not provided',
                'email': '[email protected]',
                'grade': 8,
            },

            'result1': {

                'name': 'Mike',
                'roll': 35,
                'phone': 'not provided',
                'email': '[email protected]',
                'grade': 8,
            }
        },
        'status' : 'ok',
    }

with a simple loop,

{% for result in results %}
    {{ result }}
{% endfor %}

where the results are result2, result0 and result1,

changing results to {{result.name}} to access the values, renders nothing.

How to do I render the values using the key?

thanks.

Upvotes: 0

Views: 926

Answers (1)

icktoofay
icktoofay

Reputation: 129109

results is a dictionary, and looping through a dictionary gives you the keys. To loop through the values, say so explicitly:

{% for result in results.values %}
    {{ result }}
{% endfor %}

If you want the key and the value, you can do that too, with items:

{% for key, value in results.items %}
    {# ... #}
{% endfor %}

Upvotes: 2

Related Questions