gpt4 book ai didi

python - 字典联合

转载 作者:行者123 更新时间:2023-12-05 02:33:51 25 4
gpt4 key购买 nike

我有两个字典,我正在尝试根据“dta”字典中的键执行联合。

dta = {
"msg": {
"success": "This was a successful email sent on 01/26/2022 at 11:44 AM"
},
"detailType": {
"user_info": {
"user_email": "example@email.com",
"user_name": "username",
},
"payload-info": {
"schema": {
"other_emails": "another@example.com",
"subject": "email subject line",
"body": "this is the body of the email"
}
}
}
}

other_data = {
"other_emails": "better@example.com",
"subject": "The original email subject line",
"body": "Original email body",
"reply": "reply@example.com"
}

我想对 dta 的“架构”键进行联合。但是当我尝试这个时

if "detailType" in dta:
combined_data = dta | other_data
print(combined_data)

这是我的结果

{
"msg": {"success": "This was a successful email sent on 01/26/2022 at 11:44 AM"},
"detailType": {
"user_info": {
"user_email": "example@email.com",
"user_name": "username"
},
"payload-info": {
"schema": {
"other_emails": "another@example.com",
"subject": "email subject line",
"body": "this is the body of the email",
}
},
},
"other_emails": "better@example.com",
"subject": "The original email subject line",
"body": "Original email body",
"reply": "reply@example.com",
}

但是,我正在尝试将其作为我的结果

{
'msg': {'success': 'This was a successful email sent on 01/26/2022 at 11:44 AM'},
'detailType': {
'user_info': {
'user_email': 'example@email.com',
'user_name': 'username'
},
'payload-info': {
'schema': {
'other_emails': 'better@example.com',
'subject': 'The original email subject line',
'body': 'Original email body',
'reply': 'reply@example.com'
}
}
}
}

有没有一种方法可以使用键作为起始位置来进行联合?

最佳答案

您正在将 other_data 与顶级 dta 字典合并。您应该将它与 dta['detailType']['payload-info']['schema'] 合并。所以使用:

if "detailType" in dta:
dta['detailType']['payload-info']['schema'].update(other_data)

关于python - 字典联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70870224/

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