Django template: nested dictionary for tag inside list for tag

I would like to be able to iterate over the dictionary inside the for loop in the Django template.

For this example, consider the following:

items_list = [ {'key1':'value1', 'key2':'value2'}, {'key1':'value5', 'key2':'value9'} ]

Method # 1:

{% for dict in items_list %}
    {% for key,value in dict %}
        <tr>
            <td>{{ key }}</td>
            <td>{{ value }}</td>
        </tr>
    {% endfor %}
{% endfor %}

Method # 2:

{% for dict in items_list %}
    {% for node in dict.items %}
        <tr>
            <td>{{ node.0 }}</td>
            <td>{{ node.1 }}</td>
        </tr>
    {% endfor %}
{% endfor %}

Questions

  • Why method number 1 does not work? It seems to me intuitive.
  • Am I doing this in method # 2 in order or can it cause problems later?
+5
source share
1 answer

The .items property should be used in method 1. Try the following:

{% for key,value in dict.items %}

dict.items () returns a list of key value pairs. But just dict is a dictionary. http://docs.python.org/library/stdtypes.html#dict.items

+16
source

All Articles