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

Python按索引给嵌套字典的Input对象添加UUID字段

嵌套字典按索引添加UUID的正确实现

你的代码出现KeyError: 0的核心原因有三点:

  • 直接遍历外层document字典时,enumerate(document)迭代的是字典的键名(如"R_Id"、"ContextKey"),而非你需要的ConsolidationInformation.Input列表元素
  • 访问UUID时错误地直接用uuid[i],但uuid是包含UUID键的字典,需先取出内部的列表uuid["UUID"]
  • 循环中用document作为迭代变量,覆盖了原始的嵌套字典变量,导致后续操作完全偏离预期

正确实现代码

uuid_dict = {
  "UUID": [
    "b8f2904b-dafd-4be3-9615-96bac8e16c7f",
    "1240ad39-4815-480f-8cb2-43f802ba8d4e"
  ]
}
document_data = {
  "R_Id": 304,
  "ContextKey": "Mr.Dave",
  "ConsolidationInformation": {
    "Input": [
      {
        "DocumentCode": "BS",
        "ObjectType": "Document",
        "InputContextKey": "Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358"
      },
      {
        "DocumentCode": "F16",
        "ObjectType": "Document",
        "InputContextKey": "Mr.Dave_F16.pdf2022-08-010T09:40:06.429358"
      }
    ]
  }
}

# 取出需要操作的两个列表
uuid_list = uuid_dict["UUID"]
input_items = document_data["ConsolidationInformation"]["Input"]

# 按索引配对,给每个Input元素添加DocumentUUID字段
for item, uuid_val in zip(input_items, uuid_list):
    item["DocumentUUID"] = uuid_val

# 打印验证结果(可选)
import json
print(json.dumps(document_data, indent=2))

代码逻辑说明

  1. 修改原始变量名为uuid_dict和document_data,避免循环中变量名冲突
  2. 分别提取出需要操作的UUID列表和Input列表
  3. 使用zip()函数将两个列表的元素按索引一一配对,遍历过程中给每个Input字典添加目标字段

执行后会输出你期望的结构:

{
  "R_Id": 304,
  "ContextKey": "Mr.Dave",
  "ConsolidationInformation": {
    "Input": [
      {
        "DocumentCode": "BS",
        "ObjectType": "Document",
        "InputContextKey": "Mr.Dave_HDFC.pdf2022-08-010T09:40:06.429358",
        "DocumentUUID": "b8f2904b-dafd-4be3-9615-96bac8e16c7f"
      },
      {
        "DocumentCode": "F16",
        "ObjectType": "Document",
        "InputContextKey": "Mr.Dave_F16.pdf2022-08-010T09:40:06.429358",
        "DocumentUUID": "1240ad39-4815-480f-8cb2-43f802ba8d4e"
      }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:03:35