flaiks
flaiks

Reputation: 269

Loop through dictionary with django

In Django, I have a dictionary, which contains dictionary, example:

d['dict1'] = [('1', 'some information'), ('2', 'some information')]
d['dict2'] = [('1', 'some more information'), ('2', 'some more information')]

and I need to loop through it, but each time it loops through it only grab the value of dict1 and dict2 corresponding with the loop.counter, so example

first time through it would output
1 3
and then
2 4
and so on and so forth 

I tried doing:

{% for item1, item2 in d.items %}
{{ item1.forloop.counter.value1 }}
{{ item2.forloop.counter.value1 }}
{% endfor %}

and it produces nothing.

Edit: I updated what the dict actually looks like

Upvotes: 0

Views: 455

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122326

You should turn this:

d['dict1'] = [('value1', '1'), ('value2', '2')]
d['dict2'] = [('value1', '3'), ('value2', '4')]

into this:

result = [('value1', '1', '3'), ('value2', '2', '4')]

You can do this in your view. You are basically preparing your data to be displayed in the template.

You can then iterate over the values easily:

{% for name, v1, v2 in result %}
{{ v1 }}
{{ v2 }}
{% endfor %}

Upvotes: 2

Related Questions