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))
代码逻辑说明
- 修改原始变量名为
uuid_dict和document_data,避免循环中变量名冲突 - 分别提取出需要操作的
UUID列表和Input列表 - 使用
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
相关产品推荐
相关产品推荐

