gpt4 book ai didi

Python合并两个字典而不丢失顺序

转载 作者:行者123 更新时间:2023-12-05 01:22:36 26 4
gpt4 key购买 nike

  • 我有一个字典,其中包含为如下文档生成的 UUID
{
"UUID": [
"b8f2904b-dafd-4be3-9615-96bac8e16c7f",
"1240ad39-4815-480f-8cb2-43f802ba8d4e"
]
}
  • 还有一个嵌套字典
{
"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 添加到 ['ConsolidationInformation']['Input'] 和内部 Input 作为 DocumentUUID,如何使用 for 循环映射它。我尝试在互联网上搜索,但没有找到可以满足这种嵌套条件的解决方案。
  • 预期产出
{
"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"
}
]
}
}
  • 我尝试了类似下面的方法,但结果是
Traceback (most recent call last):
File "<string>", line 26, in <module>
KeyError: 0
  • 代码
uuid = {
"UUID": [
"b8f2904b-dafd-4be3-9615-96bac8e16c7f",
"1240ad39-4815-480f-8cb2-43f802ba8d4e"
]
}
document = {
"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"
}
]
}
}
for i, document in enumerate(document):
uuid = uuid[i]
print(f"${uuid} for 1 {document}")

最佳答案

问题:您的尝试做得很好。唯一的问题是必须在正确的嵌套级别访问和添加值。

解决方案:您可以按如下方式更正您的尝试:

for i, doc in enumerate(document['ConsolidationInformation']['Input']):
doc['DocumentUUID'] = uuid['UUID'][i]

或者:您可以使用zip 函数。您可以了解有关此功能的更多信息 here .

下面是一个示例,说明如何将函数应用于您的代码:

for u, doc in zip(uuid['UUID'], document['ConsolidationInformation']['Input']):
doc['DocumentUUID'] = u

输出:输出如下:

{
"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"
}
]
}
}

关于Python合并两个字典而不丢失顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73659394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com