Django - How to do tuple unpacking in a template 'for' loop Django - How to do tuple unpacking in a template 'for' loop python python

Django - How to do tuple unpacking in a template 'for' loop


Another way is as follows.

If one has a list of tuples say:

mylst = [(a, b, c), (x, y, z), (l, m, n)]

then one can unpack this list in the template file in the following manner.In my case I had a list of tuples which contained the URL, title, and summary of a document.

{% for item in mylst %}         {{ item.0 }} {{ item.1}} {{ item.2 }}    {% endfor %}


it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists}

[ (Product_Type_1, ( product_1, product_2 )),   (Product_Type_2, ( product_3, product_4 )) ]

and have the template do this:

{% for product_type, products in product_type_list %}    {{ product_type }}    {% for product in products %}        {{ product }}    {% endfor %}{% endfor %}

the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator.each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products...


You must used this way:

{% for product_type, products in product_list.items %}    print product_type    {% for product in products %}        print product    {% endfor %}{% endfor %}

Don't forget the variable items in the dictionary data