【问题标题】:Loop through dictionary with django用 django 遍历字典
【发布时间】:2012-07-01 10:00:38
【问题描述】:

在 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 %}

它什么也没有产生。

编辑:我更新了字典的实际外观

【问题讨论】:

    标签: python django dictionary django-templates


    【解决方案1】:

    你应该转这个:

    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 %}
    

    【讨论】:

    • 好的,但我的问题是我将如何做到这一点,在我看来,它使用循环来获取所有必要的对象并将其放入字典中
    猜你喜欢
    • 2018-05-24
    • 2010-11-03
    • 2019-09-24
    • 2015-08-07
    • 2013-04-16
    • 2010-11-20
    相关资源
    最近更新 更多