【问题标题】:Generate HTML Table from Python Dictionary从 Python 字典生成 HTML 表
【发布时间】:2014-05-17 10:21:44
【问题描述】:

我如何将下面的字典转换成 html 表格

  {'Retry': ['30', '12', '12'] 'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'] Download': ['70.', '99', '90'] }

我想要实现的Html表格格式是

Retry       MAC         Download
  30      aabbccddee        70
  12      ffgghhiijj        99
  12      kkllmmnnoo        90

我已经为带有边框和所有内容的表格编写了 css,但数据未正确填充。我正在用 web2py 尝试这个。但是发现很难编写逻辑以表格格式打印上述字典。

谢谢!

【问题讨论】:

    标签: python html linux web web2py


    【解决方案1】:

    您可以通过使用 web2py TABLETR 帮助程序来简化它:

    在控制器中:

    def myfunc():
        d = {'Retry': ['30', '12', '12'],
             'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'],
             'Download': ['70.', '99', '90']}
        colnames = ['Retry', 'Station MAC', 'Download']
        rows = zip(*[d[c] for c in colnames])
        return dict(rows=rows, colnames=colnames)
    

    在视图中:

    {{=TABLE(THEAD(TR([TH(c) for c in colnames])),
             [TR(row) for row in rows]))}}
    

    【讨论】:

    • 这实际上是在元素之后创建一个额外的行。
    • 谢谢!这很棒 !但唯一的事情是额外的行
    • 太糟糕了 web2py 不能用于 python 3
    • 不知道您为什么要特别在此处发表该评论,但 Python 3 支持即将推出。
    【解决方案2】:

    使用 dict 不会保持列的顺序,但如果你没问题,那么这个例子就可以工作

    data = {'Retry': ['30', '12', '12'],
            'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'],
            'Download': ['70.', '99', '90']}
    
    html = '<table><tr><th>' + '</th><th>'.join(data.keys()) + '</th></tr>'
    
    for row in zip(*data.values()):
        html += '<tr><td>' + '</td><td>'.join(row) + '</td></tr>'
    
    html += '</table>'
    
    print html
    

    【讨论】:

    • 或者使用 data=OrderedDict() 保持顺序
    【解决方案3】:

    有点像

    d =  {'Retry': ['30', '12', '12'], 'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'], 'Download': ['70.', '99', '90']}
    
    keys = d.keys()
    length = len(d[keys[0]])
    
    items = ['<table style="width:300px">', '<tr>']
    for k in keys:
        items.append('<td>%s</td>' % k)
    items.append('</tr>')
    
    for i in range(length):
        items.append('<tr>')
        for k in keys:
            items.append('<td>%s</td>' % d[k][i])
        items.append('</tr>')
    
    items.append('</table>')
    
    print '\n'.join(items)
    

    【讨论】:

      【解决方案4】:

      对这个问题进行了相当彻底的搜索。到目前为止,我发现的最佳解决方案是由 Google 提供的 prettytable 软件包。我会举一个例子,但链接中的例子很全面。

      【讨论】:

        猜你喜欢
        • 2020-01-28
        • 2014-10-04
        • 2019-05-09
        • 1970-01-01
        • 2021-01-23
        • 2013-07-02
        • 2016-06-28
        • 2016-05-07
        • 2010-11-24
        相关资源
        最近更新 更多