You need to enable JavaScript to run this app. Python for循环添加字典元素时旧值被覆盖,如何生成ID映射color的字典
优惠活动
大模型
产品
解决方案
定价
更多

Python for循环添加字典元素时旧值被覆盖,如何生成ID映射color的字典

Python实现列表嵌套字典提取键值对生成新字典

首先明确sample_list的结构参考如下:

sample_list = [
    {"Meta": {"ID": "1234567"}, "bbb": {"color": "red"}},
    {"Meta": {"ID": "78945612"}, "bbb": {"color": "blue"}}
]

实现方法

方法1:基础for循环实现

# 初始化空结果字典
result_dict = {}
for item in sample_list:
    # 取ID作为新字典的键,取color作为对应值
    item_id = item["Meta"]["ID"]
    item_color = item["bbb"]["color"]
    result_dict[item_id] = item_color

print(result_dict)
# 输出结果:{'1234567': 'red', '78945612': 'blue'}

方法2:字典推导式(更简洁)

result_dict = {item["Meta"]["ID"]: item["bbb"]["color"] for item in sample_list}

可选兼容处理

如果实际数据中可能存在字段缺失的情况,可加判断避免抛出KeyError:

result_dict = {}
for item in sample_list:
    if "Meta" in item and "ID" in item["Meta"] and "bbb" in item and "color" in item["bbb"]:
        result_dict[item["Meta"]["ID"]] = item["bbb"]["color"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 08:57:01