首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将词典转换为HTML表格

将词典转换为HTML表格
EN

Stack Overflow用户
提问于 2018-06-07 05:13:26
回答 1查看 1.2K关注 0票数 0

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

输入

代码语言:javascript
复制
dict_data = {'x,y,z':['1','5','6'],'p,q,r':['10','25','36']}

输出:

代码语言:javascript
复制
col1     col2 col3 val1 val2

x     y    z    1     5

p     q    r        10    25
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 05:31:37

请测试以下脚本,评论中有相关解释:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50729702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档