从Python字典生成HTML表格
我想把下面这个字典转换成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 个回答
1
我对这个问题进行了相当详细的搜索。到目前为止,我找到的最佳解决方案是谷歌提供的prettytable包。虽然我想给个例子,但链接中的示例已经很全面了。
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
使用字典的话,列的顺序是不能保证的。不过如果你对此没有问题的话,这个例子是可以用的。
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
5
你可以通过使用web2py的TABLE
和TR
助手来简化一些操作:
在控制器里:
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]))}}