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

如何在Python中将列表内字典的键值对单行生成指定HTML内容?

Python实现方案

核心思路

遍历列表中的每个字典,动态获取所有键值对:先将键名转换为「下划线转空格、首字母大写」的格式,再把所有键值对拼接成一段连贯文本,最后将整段文本包裹在同一个<p>标签内。

代码实现

my_list = [
    {"user_name": "Alice", "user_age": 25, "user_city": "New York"},
    {"user_name": "Bob", "user_age": 30, "user_city": "London"}
]

def generate_combined_p_tags(data_list):
    html_output = []
    for entry in data_list:
        # 处理单个字典的所有键值对
        content_segments = []
        for key, val in entry.items():
            # 格式化键名:下划线转空格 + 首字母大写
            formatted_key = key.replace("_", " ").title()
            content_segments.append(f"{formatted_key}: {val}")
        # 拼接成完整的<p>标签
        combined_p = f"<p>{' | '.join(content_segments)}</p>"
        html_output.append(combined_p)
    return html_output

# 执行并打印结果
final_tags = generate_combined_p_tags(my_list)
for tag in final_tags:
    print(tag)

代码说明

  • 无需硬编码键名:通过entry.items()动态遍历字典的所有键值对,适配任意结构的字典
  • 键名格式转换:replace("_", " ")替换下划线为空格,title()自动将每个单词首字母大写
  • 文本拼接:用' | '.join()将多个键值对片段合并(可根据需求替换分隔符,比如, 或<br>)
  • 标签生成:将合并后的文本直接包裹在<p>标签中,每个字典对应一个独立的<p>

输出示例

运行代码后会得到以下结果:

User Name: Alice | User Age: 25 | User City: New York

User Name: Bob | User Age: 30 | User City: London

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:45:02