python - 字典联合

标签 python dictionary python-3.9

我有两个字典,我正在尝试根据“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/

相关文章:

dictionary - 返回常量字典

python - 什么是 "soft keywords"?

javascript - 数据是否自动推送到网站? (Python/Flask + WSIG + jquery AJAX)

python - pandas 按天、周或月分组以获取时间戳

python - 仅当其字符串值不为空时才将字典项添加到集合中的简便方法?

python - FastAPI 返回 AttributeError : 'dict' object has no attribute 'encode'

python - 如何为 MacOS for python 3.9 解决 "Preparing wheel metadata ... error"这个错误

python - 在 unittest 中比较(断言相等)两个包含 numpy 数组的复杂数据结构

python - 哪些类型的语言允许以编程方式创建变量名?

python - 总结 Python 中的数组字典