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

时间:2019-07-23 17:08:29

标签: python html data-structures

我目前在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属性并具有正确的行数以进行跨越。我知道这是父母拥有的孩子数量,但我似乎可以弄清楚如何编写代码。

也是第二优先级,但是如果有人认为这样做更有效,请告诉我。

 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

2 个答案:

答案 0 :(得分:2)

您提供的数据似乎不完整,因此密钥[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

答案 1 :(得分:1)

我建议对于每个单元格,以单元格名称为键,将行跨度设置为等于字典值的相应值中字典的另一个值的项数。

例如

Input:

{  
   "system":{  # span = 5 since system_apps(2) + SystemEnv(1) + System_Memory(2) = 5
      "system_apps":{ # span =  2 since it only contains systemEnv with span of 2 
         "SystemEnv":{  # span = 2 since there are 2 items (test1 object, test2 object)
           test1 object,
            test2 object
         }, 
        "SystemEnv2":{  # span = 1 since it only contains system test which has span of 1 
         "System Test":{ # span = 1 (test1 object)
           test1 object
         },
         "System Memory":{  # span = 2 since it only contains memory test which contains span of 2 
            "Memory Test":{  # span = 2 (corresponds with test3 object and test4 object)
               test3 object,
               test4 object
            }
         }
      }
   }
}

如果知道级别(假设它们都包含相同数量的级别),则将行跨度设置为从最远的子级开始的直接子级的跨度之和。不是词典的任何项目都将自动具有1的跨度,您只需添加行跨度,然后进入下一个级别,直到到达顶部。

相关问题