【问题标题】:How to convert dictionary of lists to html table?如何将列表字典转换为 html 表?
【发布时间】:2019-10-16 01:35:04
【问题描述】:

我有一个列表字典。例如:

result = {
    'a': ['x', 'y', 'z'],
    'b': ['p', 'q', 'r'],
    'c': ['m', 'n', 'o']
}

我希望 a、b 和 c 成为我的表格的标题以及该特定列下的相应列表。

我已经像这样从cherrypy将字典传递给html return tmpl.render(result = result)

补充: 这是写的html代码

<table id="myTable"> {% for k,v in result.items() %}
    <th> {{ k }}</th>
    {% for val in v %}
    <tr>
        <td> {{ val }}</td>
    </tr>
    {% endfor %} {% endfor %}
</table>

【问题讨论】:

  • 你到底面临什么问题?
  • @StephanSchrijver 输出格式不理想。标题将位于左侧,并且列表中该特定标题的所有值都显示在一行中。我想要一个 html 表格中的字典,顶部有标题,标题下有相应的列表元素。

标签: html python-3.x dictionary flask cherrypy


【解决方案1】:

根据您的逻辑,您的代码现在将执行以下操作(伪):

foreach key & value: add the key as a th,
then loop the value (because it is an array):
   add a new table row with a table cell with that 'nested' value.

这将导致以下输出:

a
0
1
2
b
0
1
2
c
0
1
2

你想做的,是(伪):

Create a tr for the headers
Loop all keys: add headers for all keys (a, b and c)
Foreach row (remember i (iterator))
    add a tr
    for each key (col) add value[i] as a td
    Close the tr
Close the table tag

我会尽力在你的代码中写这个(查看你提供的 sn-p)。 注意:尚未对此进行测试。

<table id="myTable"> 
    <tr>
      {% for k,v in results.items() %}
      <th> {{ k }}</th>
      {% endfor %}
    </tr>
    {% for i in range(0, len(results[a])) %}
    <tr>
      {% for k,v in results.items() %}
      <td>v[i]</td>
      {% endfor %}
    </tr>
    {% endfor %}
</table>

还有一些库可以为您执行此操作:https://www.decalage.info/python/html(例如)

【讨论】:

  • 非常感谢@StephanSchrijver !!!它可以工作,但“len(results[a])”必须从烧瓶传递到视图。
  • 很高兴听到!我提供的代码中有一些问题,但我相信你会明白的。例如:如果 len(results[a]) > len(results[b])。它会抛出异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2017-04-23
  • 2021-10-13
  • 2017-05-30
相关资源
最近更新 更多