【问题标题】:List of dictionaries in jinja神社词典列表
【发布时间】: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>

【问题讨论】:

  • 只需执行&lt;h1&gt;Product: {{ dict_item.product }}&lt;/h1&gt;&lt;h2&gt;Cost: {{ dict_item.cost }}&lt;/h2&gt;。不需要另一个循环。

标签: python dictionary jinja2


【解决方案1】:

试试这个:-

{% for dict_item in products %}
          <h1>Product: {{ dict_item['product'] }}</h1>
          <h2>Cost: {{ dict_item['cost'] }}</h2>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多