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

如何用Python批量修改字典键名并生成UUID?

解决方案

1. 直接实现:替换键名+添加UUID

你的问题核心是遍历Input列表时没正确替换键名(原Object*键会残留),且pop方法没作用在正确对象上。下面是直接可用的代码:

先导入UUID生成模块:

import uuid

然后处理输入字典:

# 假设pdct_input_body是你的输入字典
for doc in pdct_input_body["Input"]:
    # 替换键名,同时删除原键
    doc["DocumentType"] = doc.pop("ObjectType")
    doc["DocumentFormat"] = doc.pop("ObjectFormat")
    doc["DocumentSourceFileName"] = doc.pop("ObjectSourceFileName")
    # 生成并添加唯一UUID
    doc["UUID"] = str(uuid.uuid4())

这段代码会完成:

  • 遍历Input中的每个字典
  • 用pop移除原键并将值赋值给新键(彻底替换而非新增)
  • 为每个文档生成唯一UUID字符串

2. 为什么你的代码没生效?

  • 最初的循环只是新增键,原Object*键依然保留,并没有实现“替换”的效果;pop才是能同时删除原键的正确方法。
  • 你尝试的sample_dict['DocumentType'] = sample_dict.pop('ObjectType')失败,大概率是因为sample_dict没有指向Input列表里的具体字典对象,而是其他无关变量。

3. 递归方案(适配嵌套字典场景)

如果你的输入存在多层嵌套结构(比如Input里的字典还有子字典需要替换键名),可以用递归函数处理:

import uuid

def process_documents(obj):
    key_mapping = {
        "ObjectType": "DocumentType",
        "ObjectFormat": "DocumentFormat",
        "ObjectSourceFileName": "DocumentSourceFileName"
    }
    
    if isinstance(obj, dict):
        new_dict = {}
        for k, v in obj.items():
            # 替换键名,没有匹配则保留原键
            new_key = key_mapping.get(k, k)
            new_dict[new_key] = process_documents(v)
        # 给文档字典添加UUID
        if "DocumentType" in new_dict:
            new_dict["UUID"] = str(uuid.uuid4())
        return new_dict
    elif isinstance(obj, list):
        # 遍历列表中的每个元素
        return [process_documents(item) for item in obj]
    else:
        # 非容器类型直接返回原值
        return obj

# 处理整个输入字典
pdct_input_body = process_documents(pdct_input_body)

内容的提问来源于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 04:55:21