gpt4 book ai didi

python - 如何通过遍历 python 嵌套字典来创建 html 表

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:15 25 4
gpt4 key购买 nike

我目前在 Python 中有一个嵌套的字典对象,我想遍历它以创建一个 html 表。我已经知道该做什么的基础知识,但需要帮助来确定每列应跨越的行数。让我用一个例子来解释更多:

Input:

{
"system":{
"System Apps":{
"SystemEnv":[
'App Test',
'App Memory',
'App Test']

"SystemEnv2":{
"System Test":[
'App Test']
}},
"System Memory":{
"Memeory Test":[
'Memory Func',
'Apes Test']
}
}
}
}
}

输出: Html Table Output

问题在于放置 rowspan 属性和要跨越的正确行数。我知道这是 parent 拥有的 child 的数量,但我似乎可以弄清楚如何编码。

也是次要的,但如果有人看到更有效的方法,请告诉我。

 for level1 in dictObj:
html += "<tr>"
html += '<td>{}</td>'.format(level1)
for level2 in dictObj[level1]:
if not first_run:
html += "<tr>"
html += '<td>{}</td>'.format(level2)
first_run = True
for level3 in dictObj[level1][level2]:
if not first_run:
html += "<tr>"
html += '<td>{}</td>'.format(level3)
first_run = True
for app in dictObj[level1][level2][level3]:
if not first_run:
html += "<tr>"
first_run = True
for test in dictObj[level1][level2][level3][app]:
if not first_run:
html += "<tr>"
html += '<td>{}</td>'.format(test)
html += '<td>{}</td>'.format(app)
html += '<td>{}</td>'.format('mb')
html += '<td>{}</td>'.format(1)
html += '</tr>'
first_run = False

最佳答案

您提供的数据似乎不完整,因此键 [System][System Apps][SystemEnv2][System Test][App Test] 突出显示(它最长,每隔一个键短 1) :

data = {
"system":{
"System Apps":{
"SystemEnv":[
'App Test',
'App Memory',
'App Test'],
"SystemEnv2":{
"System Test":[
'App Test']
}
},
"System Memory":{
"Memeory Test":[
'Memory Func',
'Apes Test']
}
}
}
# }
# }

def num_items(d):
if isinstance(d, list):
for i in d:
for ii in num_items(i):
yield ii
elif isinstance(d, dict):
for k, v in d.items():
for ii in num_items(v):
yield ii
else:
yield 1

def traverse(d, cur=[]):
if isinstance(d, list):
for i in d:
cur.append( (i, sum(num_items(i))) )
for ii in traverse(i, cur):
yield ii
elif isinstance(d, dict):
for k, v in d.items():
cur.append( (k, sum(num_items(v))) )
for ii in traverse(v, cur):
yield ii
else:
yield cur
del cur[:]

print('<table border=4>')
for row in traverse(data):
print('<tr>')
for td, rowspan in row:
print('<td rowspan={}>{}</td>'.format(rowspan, td))
print('</tr>')
print('</table>')

打印:

<table border=4>
<tr>
<td rowspan=6>system</td>
<td rowspan=4>System Apps</td>
<td rowspan=3>SystemEnv</td>
<td rowspan=1>App Test</td>
</tr>
<tr>
<td rowspan=1>App Memory</td>
</tr>
<tr>
<td rowspan=1>App Test</td>
</tr>
<tr>
<td rowspan=1>SystemEnv2</td>
<td rowspan=1>System Test</td>
<td rowspan=1>App Test</td>
</tr>
<tr>
<td rowspan=2>System Memory</td>
<td rowspan=2>Memeory Test</td>
<td rowspan=1>Memory Func</td>
</tr>
<tr>
<td rowspan=1>Apes Test</td>
</tr>

在浏览器中是这样的:

enter image description here

关于python - 如何通过遍历 python 嵌套字典来创建 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com