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

Python如何基于列表生成各元素对应相同固定key的字典列表

Python列表转固定key的字典列表实现方案

需求说明

将给定列表的每个元素作为值,绑定固定keytitle,最终输出由字典组成的列表,可按需处理元素前后多余空格匹配输出要求。

实现代码

方法1:列表推导式(最简洁推荐)

# 定义原始列表
origin_list = ['King', 'President', 'VP', ' 2nd VP', '3rd VP']
# 直接生成目标列表,strip()用于去除元素前后多余空格,不需要清除空格可删掉该方法
res = [{'title': i.strip()} for i in origin_list]
print(res)

方法2:普通循环实现(逻辑更直观)

origin_list = ['King', 'President', 'VP', ' 2nd VP', '3rd VP']
res = []
for i in origin_list:
    # 不需要清除空格直接写{'title': i}即可
    res.append({'title': i.strip()})
print(res)

运行输出

两种方法的输出完全一致,符合要求:

[{'title':'King'}, {'title':'President'}, {'title':'VP'}, {'title':'2nd VP'}, {'title':'3rd VP'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:45:08