字典联合

Union for dictionaries at a key

我有两个字典,我正在尝试根据“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 与 top-level dta 词典合并。您应该将它与 dta['detailType']['payload-info']['schema'] 合并。所以使用:

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