You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典转HTML无序列表:嵌套结构渲染问题及通用方案需求

解决方案

要实现嵌套字典和列表到HTML无序列表的正确转换,需要修改递归逻辑,同时处理字典和列表类型,并保留可读性格式。以下是适配两种字典结构的通用函数:

def dict_to_html_ul(data, level=0):
    indent = '    ' * level
    next_indent = '    ' * (level + 1)
    
    if isinstance(data, dict):
        html = f'{indent}<ul>\n'
        for key, value in data.items():
            value_html = dict_to_html_ul(value, level + 1)
            html += f'{next_indent}<li><b>{key}</b>: '
            # 嵌套结构换行显示
            if isinstance(value, (dict, list)):
                html += '\n' + value_html + f'\n{next_indent}</li>\n'
            else:
                html += f'{value_html}</li>\n'
        html += f'{indent}</ul>'
        return html
    elif isinstance(data, list):
        if not data:
            return '[]'
        html = f'{indent}<ul>\n'
        for idx, item in enumerate(data):
            if isinstance(item, dict):
                # 提取字典的内部<li>元素,不包裹额外<ul>
                dict_html = dict_to_html_ul(item, level + 1)
                inner_lines = dict_html.split('\n')[1:-1]
                for line in inner_lines:
                    html += f'{line}\n'
                # 列表中字典项之间添加分隔线
                if idx != len(data) - 1:
                    html += f'{next_indent}<br>\n'
            else:
                item_html = dict_to_html_ul(item, level + 1)
                if isinstance(item, (dict, list)):
                    html += f'{next_indent}<li>\n{item_html}\n{next_indent}</li>\n'
                else:
                    html += f'{next_indent}<li>{item_html}</li>\n'
        html += f'{indent}</ul>'
        return html
    else:
        # 处理布尔值为小写,匹配JSON格式
        if isinstance(data, bool):
            return str(data).lower()
        return str(data)

核心改进点

  1. 递归处理列表:不再将列表转为JSON字符串,而是递归渲染为嵌套列表
  2. 字典列表项合并:列表中的字典项直接展开为<li>元素,用<br>分隔不同字典的内容,匹配你期望的格式
  3. 缩进格式化:根据嵌套层级添加缩进,生成可读性强的HTML代码
  4. 布尔值处理:自动将Python的True/False转为小写的true/false,符合示例输出要求

使用示例

调用函数时直接传入目标字典即可:

# 第一个测试字典
input_dict = {
    'dataStreamId': 'raw:com.google.nutrition:NutritionSource',
    'dataStreamName': 'NutritionSource',
    'type': 'raw',
    'dataType': {
        'name': 'com.google.nutrition',
        'field': [
            {'name': 'nutrients', 'format': 'map'},
            {'name': 'meal_type', 'format': 'integer', 'optional': True},
            {'name': 'food_item', 'format': 'string', 'optional': True}
        ]
    },
    'application': {
        'version': '1',
        'detailsUrl': 'http://example.com',
        'name': 'My Example App'
    },
    'dataQualityStandard': []
}

print(dict_to_html_ul(input_dict))

# 第二个测试字典
a = {'minStartTimeNs': '1573159699023000000', 'maxEndTimeNs': '1573159699023999000', 'dataSourceId': 'raw:com.google.nutrition:NutritionSource', 'point': [{'startTimeNanos': '1573159699023000000', 'endTimeNanos': '1573159699023999000', 'dataTypeName': 'com.google.nutrition', 'value': [{'mapVal': [{'key': 'fat.total', 'value': {'fpVal': 0.4}}, {'key': 'sodium', 'value': {'fpVal': 1}}, {'key': 'fat.saturated', 'value': {'fpVal': 0.1}}, {'key': 'protein', 'value': {'fpVal': 1.3}}, {'key': 'carbs.total', 'value': {'fpVal': 27}}, {'key': 'cholesterol', 'value': {'fpVal': 0}}, {'key': 'calories', 'value': {'fpVal': 105}}, {'key': 'sugar', 'value': {'fpVal': 14}}, {'key': 'dietary_fiber', 'value': {'fpVal': 3.1}}, {'key': 'potassium', 'value': {'fpVal': 422}}]}, {'intVal': 4, 'mapVal': []}, {'stringVal': 'apple', 'mapVal': []}]}]}

print(dict_to_html_ul(a))

生成的HTML会完全匹配你期望的嵌套列表格式,同时正确处理所有层级的嵌套结构。

内容的提问来源于stack exchange,提问作者docksdocks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:20:26