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

如何将字符串列表转换为含固定键的单键字典列表?

实现方法

要将列表 ['red', 'blue'] 转换为每个元素是单键字典(固定键为color)的列表,有两种常用方式:

方法一:列表推导式(简洁高效)

这是Python中处理这类转换最常用的写法,一行代码就能完成:

original_list = ['red', 'blue']
target_list = [{'color': color_str} for color_str in original_list]

执行后target_list的值就是:[{'color': 'red'}, {'color': 'blue'}]

方法二:普通循环(适合新手理解)

如果需要更直观的逻辑展示,可以用for循环逐个构建字典并添加到结果列表:

original_list = ['red', 'blue']
target_list = []
for color_str in original_list:
    target_list.append({'color': color_str})

运行后同样能得到目标格式的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:09:38