从Python字典生成HTML表格

6
我该如何将下面的字典转换成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解决这个问题,但很难编写逻辑以表格格式打印上述字典。

谢谢!

4个回答

5
您可以使用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]))}}

这实际上是在元素后面创建了一行。 - Error_Coding
谢谢!这很棒!但唯一的问题是需要添加一行。 - Error_Coding
很遗憾,web2py还不支持Python 3。 - Bryce Guinta
1
不确定为什么你会在这里发布那条评论,但是Python 3的支持很快就会到来。 - Anthony

4
使用字典将不会保持列的顺序,但如果您可以接受这一点,那么此示例将起作用。
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() 保持顺序。 - jonincanada

3

Something like

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)

1

我对这个问题进行了彻底的搜索。到目前为止,我发现最好的解决方案是由Google提供的prettytable包。我不会给出示例,但链接中的示例非常全面。


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