0

在 Django 中,我有一个字典,其中包含字典,例如:

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

我需要循环遍历它,但是每次循环遍历它只获取与loop.counter对应的dict1和dict2的值,所以例如

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

我试着做:

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

它什么也没有产生。

编辑:我更新了字典的实际样子

4

1 回答 1

2

你应该把这个:

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

进入这个:

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

您可以在您的视图中执行此操作。您基本上是在准备要在模板中显示的数据。

然后,您可以轻松地迭代这些值:

{% for name, v1, v2 in result %}
{{ v1 }}
{{ v2 }}
{% endfor %}
于 2012-06-29T21:26:34.740 回答