Python字典转换为HTML表格

29

有没有办法将Python字典打印为HTML表格?我有一个Python字典,并使用它将其发送到HTML中。

return render_template('index.html',result=result)

现在我需要将结果字典中的元素打印到HTML中,以表格形式呈现。


正在使用Python Flask Web框架。 - just_in
1
Flask使用Jinja。阅读手册http://jinja.pocoo.org/docs/templates/。 - Sean McSomething
7个回答

52

Flask使用Jinja作为模板框架。您可以在模板(html)中执行以下操作:

Jinja也可以作为标记渲染器单独使用。

Python3 / Jinja2

<table>
  <thead>
    <tr>
      <th>Key</th>
      <th>Value</th>
    </tr>
  </thead>
  <tbody>
  {% for key, value in result.items() %}
   <tr>
       <td> {{ key }} </td>
       <td> {{ value }} </td>
   </tr>
  {% endfor %}
  </tbody>
</table>

Python2/Jinja

<table>
{% for key, value in result.iteritems() %}
   <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
   </tr>
{% endfor %}
</table>

17
对于Python3,您可以使用result.items() - Frane

6

请查看Flask-Table

文档中的示例(稍作编辑):

from flask_table import Table, Col

# Declare your table
class ItemTable(Table):
    name = Col('Name')
    description = Col('Description')

items = [dict(name='Name1', description='Description1'),
         dict(name='Name2', description='Description2'),
         dict(name='Name3', description='Description3')]

# Populate the table
table = ItemTable(items)

# Print the html
print(table.__html__())
# or just {{ table }} from within a Jinja template

5

我发现将字典放入一个列表中更为顺利,然后让HTML通过循环遍历列表并打印表格。 Python代码如下:

Table = []
for key, value in results_dict.iteritems():    # or .items() in Python 3
    temp = []
    temp.extend([key,value])  #Note that this will change depending on the structure of your dictionary
    Table.append(temp)

然后在你的HTML中循环遍历表格。
<table>
{% for t in table %}
    <tr>
    {% for i in t %}
        <td>{{ i }}</td>
    {% endfor %}
    </tr>
{% endfor %}
 </table>

我需要使表格中只有特定的单元格可编辑。另外,我想在某些单元格上添加 'datetimepicker.js' 模块。有什么办法吗? - just_in
所以你可以将表格中可编辑的单元格制作成一个文本框,其默认值为字典中的任何内容。你可以给文本框一个唯一的ID,这样datetimepicker就可以获取你想要更改的单元格。 - Jroosterman

4

因为需要发邮件,所以我希望有一个简单的方式用Python字典生成只含内联样式的HTML代码。但是我找不到满意的解决方案,于是我自己编写了这个程序。

这个程序非常易于使用,并且添加样式也很简单。

<table style="margin: 3px">
    <tr style="background-color: #7cc3a97d">
        <th style="color: white">col1</th>
        <th style="color: white">col2</th>
        <th style="color: white">col3</th>
        <th style="color: white">col4</th>
    </tr>

    <tr style="background-color: aliceblue">
        <td style="padding: 1rem">value11</td>
        <td style="padding: 1rem">value21</td>
        <td style="padding: 1rem">value31</td>
        <td style="padding: 1rem">value41</td>
    </tr>
    <tr style="background-color: #c2d4e4">
        <td style="padding: 1rem">value12</td>
        <td style="padding: 1rem">value22</td>
        <td style="padding: 1rem">value32</td>
        <td style="padding: 1rem">value42</td>
    </tr>
    <tr style="background-color: aliceblue">
        <td style="padding: 1rem">value13</td>
        <td style="padding: 1rem">value23</td>
        <td style="padding: 1rem">value33</td>
        <td style="padding: 1rem">value43</td>
    </tr>
</table>

假设你有以下字典:
myDict = {
    'col1' : ['value11', 'value12', 'value13'],
    'col2' : ['value21', 'value22', 'value23'],
    'col3' : ['value31', 'value32', 'value33'],
    'col4' : ['value41', 'value42', 'value43'],
}

可以通过以下方式将其转换为IT技术:

class HTML:

    def __init__(self, Header, tableStyles = {}, trStyles = {}, thStyles = {}):
        self.tableStyles = HTML._styleConverter(tableStyles)
        trStyles = HTML._styleConverter(trStyles)
        thStyles = HTML._styleConverter(thStyles)
        self.rows = []
        self.Header= f'<tr {trStyles} >'
        for th in Header:
            self.Header += f'\n<th {thStyles} >{th}</th>'
        self.Header += '\n</tr>'

    @staticmethod
    def _styleConverter(styleDict : dict):
        if styleDict == {}:
            return ''
        styles = ''
        for [style, value] in styleDict.items():
            styles +=f'{style}: {value};'
        return f'style="{styles}"'

    def addRow(self, row, trStyles = {}, tdStyles = {}):
        trStyles = HTML._styleConverter(trStyles)
        tdStyles = HTML._styleConverter(tdStyles)
        temp_row = f'\n<tr {trStyles} >'
        for td in row:
            temp_row += f'\n<td {tdStyles} >{td}</td>'
        temp_row += '\n</tr>'
        self.rows.append(temp_row)


    def __str__(self):


        return \
f'''
<table {self.tableStyles} >
{self.Header}
{''.join(self.rows)}
</table>
'''



def dictionaryToHTMLTable(dict : dict):
    html = HTML(Header = dict.keys(),
                tableStyles={'margin': '3px'},
                trStyles={'background-color': '#7cc3a97d'},
                thStyles={ 'color': 'white'})
    for i, row in enumerate(zip(*dict.values())):
        print(row)
        if i%2 == 0:
            BGC = 'aliceblue'
        else:
            BGC = '#c2d4e4'
        html.addRow(row, trStyles={'background-color' : BGC}, tdStyles={'padding': '1rem'})
    return html

并输出
print(dictionaryToHTMLTable(myDict))


非常感谢,如果字典值的长度不相等会发生什么,例如 {"no_login": ["abc","bcd","cfg"], "no_report": ["1","2","3"], "no_link": ["hello","hii"]}。 - Prarthan Ramesh
@PrarthanRamesh 我运行了你的示例,它工作得很好,您可能希望在函数dictionaryToHTMLTable内添加一些样式来将文本居中。 - coder
谢谢,我进行了一些代码更改,使得所有列表长度相同,以使表格单元格不会显得有点偏移。 - Prarthan Ramesh

2
对于Python3,在result.items后面不需要加括号。
<table>
{% for key, value in result.items %}
   <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
   </tr>
{% endfor %}
</table>

你需要使用items()而不是items。 - Raj Verma

1
通过使用 result.iteritems() 遍历字典项,然后将键/数据写入 HTML 表格的行中。

我们需要在 HTML 页面中使用 result.iteritems 吗?有文件可以参考吗? - just_in

1
#!/usr/bin/env python3

tbl_fmt = '''
<table> {}
</table>'''

row_fmt = '''
  <tr>
    <td>{}</td>
    <td>{}</td>
  </tr>'''


def dict_to_html_table(in_dict):
    return tbl_fmt.format(''.join(row_fmt.format(k, v) for k, v in in_dict.items()))


if __name__ == "__main__":
    d = {key: value for value, key in enumerate("abcdefg")}
    print(d)
    print(dict_to_html_table(d))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接