如何将字符串列表转换为含固定键的单键字典列表?
实现方法
要将列表 ['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
相关产品推荐
相关产品推荐

