我是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
发布于 2018-06-07 05:31:37
请测试以下脚本,评论中有相关解释:
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
https://stackoverflow.com/questions/50729702
复制相似问题