首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关键词典联盟

关键词典联盟
EN

Stack Overflow用户
提问于 2022-01-26 21:03:48
回答 1查看 70关注 0票数 3

我有两本字典,我正试图根据"dta“字典中的一个键来执行一个联合。

代码语言:javascript
复制
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的“模式”键。然而,当我尝试这个

代码语言:javascript
复制
if "detailType" in dta:
    combined_data = dta | other_data
    print(combined_data)

这是我的结果

代码语言:javascript
复制
{
    "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",
}

然而,我正试图把这个作为我的结果

代码语言:javascript
复制
{
    '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'
            }
        }
    }
}

有没有办法用钥匙作为起点来做一个联合呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-26 21:10:28

您正在将other_data与顶级dta字典合并。您应该将其与dta['detailType']['payload-info']['schema']合并。因此,请使用:

代码语言:javascript
复制
if "detailType" in dta:
    dta['detailType']['payload-info']['schema'].update(other_data)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70870224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档