Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to loop over two lists simultaneously in django?

I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie.

{% for i,j in table, total %} 
 {{ i }} 
 {{ j }}
{% endfor %} 

or something similar?

like image 385
mike Avatar asked Feb 12 '13 20:02

mike


People also ask

How do I iterate two lists at the same time in python?

Use the izip() Function to Iterate Over Two Lists in Python It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.

Can I use while loop in Django?

The key point is that you can't do this kind of thing in the Django template language.


3 Answers

If both lists are of the same length, you can return zipped_data = zip(table, total) as template context in your view, which produces a list of 2-valued tuples.

Example:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> zip(lst1, lst2)
[('a', 1), ('b', 2), ('c', 3)]

In your template, you can then write:

{% for i, j in zipped_data %}
    {{ i }}, {{ j }}
{% endfor %}

Also, take a look at Django's documentation about the for template tag here. It mentions all possibilities that you have for using it including nice examples.

like image 73
pemistahl Avatar answered Sep 23 '22 14:09

pemistahl


For any recent visitors to this question, forloop.parentloop can mimic the zipping of two lists together:

{% for a in list_a %}{% for b in list_b %}
    {% if forloop.counter == forloop.parentloop.counter %}
        {{a}} {{b}}
    {% endif %}
{% endfor %}{% endfor %}
like image 41
Melipone Avatar answered Sep 22 '22 14:09

Melipone


Use python's zip function and zip the 2 lists together.

In your view:

zip(table, list)

In your template, you can iterate this like a simple list, and use the .0 and .1 properties to access the data from table and list, respectively.

like image 27
Jordan Avatar answered Sep 19 '22 14:09

Jordan