如何将DECT转换为HTML表?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (58)

我是Python的新手,我想把下面的字典转换成python的html表格格式。请告诉我实现这一目标的有效方法。

输入

dict_data = {'x,y,z':['1','5','6'],'p,q,r':['10','25','36']}

产出:

col1     col2 col3 val1 val2

x     y    z    1     5

p     q    r        10    25
提问于
用户回答回答于

请测试以下脚本,注释中有说明:

dict_data = {'x,y,z':['1','5','6'],'p,q,r':['10','25','36']}

# Here I prepare the html variable I will be updating later
html = '<table style="width:100%">'

# Let's cycle the elements in dict_data
for dict_item in dict_data:
    html += '<tr>'
    # Using split I unpack the values in the key using the , as delimiter
    key_values = dict_item.split(',')
    # Time to fill the table rows with the single key subunits
    html += '<th>' + key_values[0] + '</th>'
    html += '<th>' + key_values[1] + '</th>'
    html += '<th>' + key_values[2] + '</th>'
    # Then we access the 1st element of dict_item key in dict_data
    html += '<th>' + dict_data[dict_item][0] + '</th>'
    # And then the 2nd 
    html += '<th>' + dict_data[dict_item][1] + '</th>'
    # Let's mark the end of the row before the next loop (if any)
    html += '</tr>'
# Do not forget to close the table too
html += '</table>'    
# Here's the final result    
print html

扫码关注云+社区

领取腾讯云代金券