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

如何合并含重复键的列表生成嵌套字典列表(避免覆盖)

问题:合并两个列表为嵌套字典列表(避免键覆盖)

原始数据定义

animal_list = [{'animal': 'dog', 'color': 'black'},
 {'animal': 'cat', 'color': 'brown'}]

outer_list = ['pet', 'pet']

期望输出

[
{'pet':{'animal': 'dog', 'color': 'black'}},
{'pet':{'animal': 'cat', 'color': 'brown'}}
]

失败的尝试代码及结果

尝试用dict(zip(...))的方式,但因为外层键重复,最终只保留了最后一条记录:

attempt_list = []
attempt_list.append(dict(zip(outer_list,animal_list)))

# 失败输出
[{'pet': {'animal': 'cat', 'color': 'brown'}}]

解决方案

问题出在dict(zip(...))会强制让字典键唯一,相同键会直接覆盖之前的条目。要实现每个键值对单独成为列表里的一个字典元素,只需要循环遍历两个列表的配对项,逐个生成字典并添加到结果列表即可:

result_list = []
# 遍历outer_list和animal_list的配对元素
for key, animal_dict in zip(outer_list, animal_list):
    # 每次生成一个包含单个键值对的字典,添加到结果列表
    result_list.append({key: animal_dict})

print(result_list)

执行后输出就是期望的结果:

[
{'pet':{'animal': 'dog', 'color': 'black'}},
{'pet':{'animal': 'cat', 'color': 'brown'}}
]

也可以用列表推导式简化代码,效果完全一致:

result_list = [{key: animal_dict} for key, animal_dict in zip(outer_list, animal_list)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:09:50