如何遍历list of list of dictionaries?将图查询结果转为可迭代字典列表
解决方案:扁平化嵌套字典列表并按需添加键值对
我来帮你搞定这个问题!你现在的核心痛点是把嵌套的字典列表拉平成可直接迭代的单一列表,同时还要根据label条件给字典添加新的键值对。咱们一步步来解决:
1. 先扁平化嵌套列表
你之前用的[x[0] for x in my_list]只提取了每个子列表的第一个元素,所以结果还是嵌套结构。要把所有子列表里的字典都取出来,变成一个单层列表,用双层列表推导式就可以:
my_list = [[{'name': 'John', 'id': 4, 'label': ['person']}, {'name': 'Peter', 'id': 20, 'label': ['bot']}, {'name': 'Lili', 'id': 24, 'label': ['person']}]] # 扁平化操作 flattened_list = [item for sublist in my_list for item in sublist]
执行后flattened_list就是你要的单层字典列表:
[ {'name': 'John', 'id': 4, 'label': ['person']}, {'name': 'Peter', 'id': 20, 'label': ['bot']}, {'name': 'Lili', 'id': 24, 'label': ['person']} ]
2. 根据label条件添加键值对
接下来遍历这个扁平化后的列表,根据你的label条件给字典添加image键。比如假设你想给所有label包含person的字典添加图片源,有两种写法:
方式一:直接修改原字典
如果不介意修改原数据,用普通循环最直观:
image_source = "your_image_path_or_url" # 替换成你的实际图片源 for item in flattened_list: # 这里可以替换成你实际的label判断条件 if 'person' in item['label']: item['image'] = image_source
方式二:生成新字典(不修改原数据)
如果想保留原数据不变,可以用字典解包+列表推导式生成新列表:
image_source = "your_image_path_or_url" updated_list = [ {**item, 'image': image_source} if 'person' in item['label'] else item for item in flattened_list ]
3. 两步合并(可选)
你也可以把扁平化和更新操作合并成一步,减少中间变量:
image_source = "your_image_path_or_url" my_new_list = [ {**item, 'image': image_source} if 'person' in item['label'] else item for sublist in my_list for item in sublist ]
这样my_new_list就是最终你需要的、可直接迭代的字典列表啦!
内容的提问来源于stack exchange,提问作者Veselin Vasilev
相关产品推荐
相关产品推荐

