【发布时间】:2016-08-04 10:41:10
【问题描述】:
我想使用 jinja 遍历字典列表。
这是我的清单:
[{'product': 'EC2', 'cost': 3.5145240400000013}, {'product': 'ElastiCache', 'cost': 1.632000000000001}, {'product': 'Elasticsearch', 'cost': 4.423768260000001}, {'product': 'RDS', 'cost': 1.632000000000001}]
我的模板:
{% for dict_item in products %}
{% for product, cost in dict_item.items() %}
<h1>Product: {{ product }}</h1>
<h2>Cost: {{ cost }}</h2>
{% endfor %}
{% endfor %}
最后是输出:
<h1>Product: product</h1>
<h2>Cost: EC2</h2>
<h1>Product: cost</h1>
<h2>Cost: 3.51452404</h2>
<h1>Product: product</h1>
<h2>Cost: ElastiCache</h2>
<h1>Product: cost</h1>
<h2>Cost: 1.632</h2>
<h1>Product: product</h1>
<h2>Cost: Elasticsearch</h2>
<h1>Product: cost</h1>
<h2>Cost: 4.42376826</h2>
<h1>Product: product</h1>
<h2>Cost: RDS</h2>
<h1>Product: cost</h1>
<h2>Cost: 1.632</h2>
如您所见,该输出有问题。所有的数据都混在一起了,我不明白为什么。
我只想要这样的东西:
<h1>Product: EC2</h1>
<h2>Cost: 3.5145240400000013</h2>
【问题讨论】:
-
只需执行
<h1>Product: {{ dict_item.product }}</h1>和<h2>Cost: {{ dict_item.cost }}</h2>。不需要另一个循环。
标签: python dictionary jinja2