简体   繁体   English

从Python Dictionary生成HTML表

[英]Generate HTML Table from Python Dictionary

How would I convert below dictionary into html table 如何将字典转换为html表格

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

Html table format I am trying to achieve is 我试图实现的Html表格式是

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

I have written css for table with border and everything, but data is not getting filled correctly. 我已经为包含边框和所有内容的表编写了css,但数据未正确填充。 I am trying this with web2py. 我正在尝试使用web2py。 But Finding difficult to write logic to print above dictionary in table format. 但是发现难以编写逻辑以表格格式打印在字典之上。

Thanks ! 谢谢 !

You can make it a little easier by using the web2py TABLE and TR helpers: 您可以使用web2py TABLETR帮助程序使其更容易一些:

In the controller: 在控制器中:

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)

And in the view: 在视图中:

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

Using a dict won't maintain the order of your columns but if you are ok with that then this example will work 使用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

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)

Had quite a thorough search regarding this issue. 对此问题进行了彻底的搜索。 By far the best solution I found was the prettytable package courtesy of Google. 到目前为止,我找到的最佳解决方案是Google提供的精美套餐。 I'd give an example, but the ones in the link are comprehensive. 我举个例子,但链接中的内容很全面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM