【问题标题】:How to iterate through list inside Dictionary in Django Python如何在 Django Python 中遍历 Dictionary 内的列表
【发布时间】:2017-01-14 04:18:29
【问题描述】:

我通过了一本结构类似的字典

dic={'items':[1,2,3,4,5], 'price':[20,30,40,50,60]}
return render_to_response('somepage.html',dic)

从我的模板 somepage.htm 我希望输出像

1  20
2  30
3  40
4  50
5  60

我应该在 somepage.html 中写什么代码来获得这个输出。

【问题讨论】:

标签: python django list dictionary iteration


【解决方案1】:

先使用zip,然后在你的模板中渲染:

dic={'items':[1,2,3,4,5], 'price':[20,30,40,50,60]}
dic['items_and_prices'] = zip(dic['items'], dic['prices'])
return render_to_response('somepage.html',dic)

模板:

{% for item, price in items_and_prices %}
    {{ item }} {{ price }}
{% endfor %}

【讨论】:

  • 这应该是公认的答案。它非常简洁、干净,是 pythonic 的方式。
【解决方案2】:

查看:

 dic={'items':[1,2,3,4,5], 'price':[20,30,40,50,60]}
 lista = []

 for i in dic["items"]:
     l = []
     l.append(i)
     lista.append(l)

 var = 1
 cont = 0

 for i in dic["price"]:
     lista[cont].append(i)
     var+=2
     cont+=1

模板:

    {% for i in lista %}
        {{ i.0 }}-{{ i.1 }}<br>
    {% endfor %}

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 2011-04-26
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多