【问题标题】:How to loop through dictionary in jinja template如何在 jinja 模板中循环遍历字典
【发布时间】:2018-08-17 14:08:44
【问题描述】:

我有一本看起来像这样的字典:

{
 'Team Starwars': {'Luke Skywalker': {('Jedi', 100)}}
 'Team helloworld': {'Beginner': {('newbie', 100)}}
}

现在我想在模板中使用 jinja 遍历字典。 我已经尝试了一些东西,但无法正确地遍历它。 我现在的代码如下所示:

  {% for team_name in team_resource %}
          {% for team, name in team_resource.items %}
                  {% for role, allocation in subrole %}
                    {% if forloop.counter0 != 0 %}<br>{% endif %}
                    {{role}} {{allocation}} %
           {% endfor %}

  {% endfor %}

team_resource 是我传递给模板的字典,在第一个循环中,我可以访问字典的第一部分并像 Team Starwars 和 Team helloworld' 一样打印出来,但无法访问字典的其余部分。

我应该怎么做?

【问题讨论】:

    标签: python dictionary set jinja2


    【解决方案1】:

    您应该使用team_resource.items() 而不是team_resource.items 来访问字典项。

    【讨论】:

    • 我不知道我是否使用其他版本,但我无法使用 items() 而不会出错
    • 我明白了。尝试改用iteritems() 方法。
    • 请注意,iteritems() 不在 Python 3 中。
    • 通过items()后如何访问字典对象?
    【解决方案2】:

    您所说的“字典的其余部分”实际上是您成功检索到的密钥的值。

    未经测试,我相信变量 name 在您的示例中是包含字典中 {'Luke Skywalker': {('Jedi', 100)} 部分的变量。

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 2016-08-31
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2023-04-03
      • 2023-03-12
      • 2022-09-22
      相关资源
      最近更新 更多