I got the following Python dictionary:
d = {'DataType': 'XY', 'DataReportGrp': {'NoSides_1': {'Side': '2', 'Reports': {'NoReportIDs_1': {'ReportID': '250001'}, 'NoReportIDs_2': {'ReportID': '250002'}}}}}
I want to transform it into an HTML list similar to this:
<li> DataType </li>
<li> DataReportGrp </li>
<ul>
<li> NoSides_1 </li>
<ul>
<li> Side </li>
<li> Reports </li>
<ul>
<li> NoReportIDs_1 </li>
<ul>
<li> ReportID </li>
</ul>
<li> NoReportIDs_2 </li>
<ul>
<li> ReportID </li>
</ul>
</ul>
</ul>
</ul>
I tried to do this with the below code. Unfortunately I do not know what logic to implement to find out when to close the </ul> group at the right time and it might be that this dictionary gets more nested levels in the future:
def nested_groups(levels):
groups = list()
def going_through(d):
if isinstance(levels, dict):
for kd, kv in d.items():
if isinstance(kv, dict):
groups.append(kd)
print(f" <li> --- {kd} </li>")
print(" <ul>")
going_through(kv)
else:
print(f" <li> --- {kd} </li>")
going_through(levels)
print("</ul>" * len(groups))
This results into:
<li> --- DataType </li>
<li> --- DataReportGrp </li>
<ul>
<li> --- NoSides_1 </li>
<ul>
<li> --- Side </li>
<li> --- Reports </li>
<ul>
<li> --- NoReportIDs_1 </li>
<ul>
<li> --- ReportID </li>
<li> --- NoReportIDs_2 </li>
<ul>
<li> --- ReportID </li>
</ul></ul></ul></ul></ul>
Some help would be appreciated.