[英]Generate HTML Table from Python Dictionary
如何將字典轉換為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。 但是發現難以編寫邏輯以表格格式打印在字典之上。
謝謝 !
您可以使用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]))}}
使用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
就像是
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)
對此問題進行了徹底的搜索。 到目前為止,我找到的最佳解決方案是Google提供的精美套餐。 我舉個例子,但鏈接中的內容很全面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.