从Python Dictionary生成HTML表

时间:2014-04-04 22:28:00

标签: python html linux web web2py

如何将字典转换为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 个答案:

答案 0 :(得分: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]))}}

答案 1 :(得分:3)

使用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

答案 2 :(得分:2)

这样的东西
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)

答案 3 :(得分:0)

对此问题进行了彻底的搜索。到目前为止,我找到的最佳解决方案是Google提供的prettytable软件包。我举了一个例子,但链接中的内容是全面的。