【问题标题】:Using a Python dictionary with multiple values, how can you output the data in a table with Jinja's for loops?使用具有多个值的 Python 字典,如何使用 Jinja 的 for 循环将数据输出到表中?
【发布时间】:2021-08-29 01:36:43
【问题描述】:

我正在使用 Django 为当前排行榜中的排名发出 API 请求。我想将此数据显示为 HTML 中的表格。这是我在 views.py 中用来制作 Python 字典的代码。

# Receive the json response
    response = json.loads(connection.getresponse().read().decode())
# Declare the dict to use
    current_table = {"position": [], "team":[], "points":[]}
    
# Loop over 20 times as there are 20 teams in the league
    for x in range(20):
        team = response["standings"][0]["table"][x]["team"]["name"]
        points = response["standings"][0]["table"][x]["points"]
        current_table["position"].append(x + 1)
        current_table["team"].append(team)
        current_table["points"].append(points)
    return render(request, "predict/index.html", {
        "table": current_table, 
    })

终端中 dict 的原始输出以及使用 jinja 的 {{ table }} 是

{'position': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 'team': ['Manchester City FC', 'Manchester United FC', 'Liverpool FC', 'Chelsea FC', 'Leicester City FC', 'West Ham United FC', 'Tottenham Hotspur FC', 'Arsenal FC', 
'Leeds United FC', 'Everton FC', 'Aston Villa FC', 'Newcastle United FC', 'Wolverhampton Wanderers FC', 'Crystal Palace FC', 'Southampton FC', 'Brighton & Hove Albion FC', 'Burnley FC', 'Fulham FC', 'West Bromwich Albion FC', 'Sheffield United FC'], 'points': [86, 74, 69, 67, 66, 65, 62, 61, 59, 59, 55, 45, 45, 44, 43, 41, 39, 28, 26, 23]}

我觉得应该有一种优雅的方式来做到这一点,因为数据就在那里。理想情况下,我想在 index.html 中使用与此类似的东西。

<table>
    <tr>
        <th>Position</th>
        <th>Team</th>
        <th>Points</th>
    </tr>
    {% for x in table %}
    <tr>
       <td>{{ x.position }}</td>
       <td>{{ x.team }}</td>
       <td>{{ x.points }}</td>
    </tr>
    {% endfor %}
</table>

但是,这不起作用,并且似乎认为只有 3 个循环可以通过(因为 dict 有 3 个键?)。我想我可能不得不重新考虑我在 Python 中制作 dict 的方式,因为通常不意味着每个值有多个键?我曾尝试在 Jinja 中使用 .items(),但它似乎不喜欢表明 dict 输出可能有问题的括号?

我想我的问题可以通过 SQL 表或 Django 模型来解决,但由于我使用的是 API,我不知道表持续更新是否是个好主意?

我的主要问题是,我找到了一种显示数据的方法,但只能一次访问一列。有没有办法将 jinja 中的这 3 个循环合并为一个,以免数据陷入彼此的循环中?

{% for x in table.position %}
{% for y in table.team %}
{% for z in table.points %}
<tr>
    <td>{{ x }}</td>
    <td>{{ y }}</td>
    <td>{{ z }}</td>
</tr>
{% endfor %}
{% endfor %}
{% endfor %}

这是我在这里的第一篇文章,如果我需要提供任何其他信息,请告诉我。

【问题讨论】:

    标签: python django loops dictionary jinja2


    【解决方案1】:

    好的 - 一个更容易使用的数据结构是这样的:

    teams = [
      {
        "position" : 1,
        "name" : "Manchester City FC",
        "points" : 86
      },
      {
        "position" : 2,
        "name" : "Manchester United FC",
        "points" : 74
      },
      ...
    ]
    

    然后,在您的模板中,您可以:

    ...
    <table>
      <thead>
        <tr>
          <th> Position </th>
          <th> Team </th>
          <th> Points </th>
        </tr>
      </thead>
      <tbody>
        {% for team in teams %}
        <tr>
          <td> {{ team.position }} </td>
          <td> {{ team.name }} </td>
          <td> {{ team.points }} </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    

    所以让我们像这样改变我们与 api 交互的方式:

    # Receive the json response:
    response = json.loads(connection.getresponse().read().decode())
    
    # initialize an empty list (not a dictionary):
    teams = []
        
    # Loop over 20 times as there are 20 teams in the league
    for x in range(20):
    
        # initialize an empty team dictionary:
        team = {}
    
        # set position:
        team["position"] = x + 1
    
        # set name:
        team["name"] = response["standings"][0]["table"][x]["team"]["name"]
        
        # set points:
        team["points"] = response["standings"][0]["table"][x]["points"]
    
        # finally, append the team dictionary to the teams list:
        teams.append(team)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2017-04-05
      相关资源
      最近更新 更多