【问题标题】:Union for dictionaries at a key一键字典联合
【发布时间】:2022-01-26 21:03:48
【问题描述】:

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

有没有办法使用键作为起始点来进行联合?

【问题讨论】:

  • 联合是必要的还是你只是在那个键上完全替换它?

标签: python dictionary python-3.9


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2011-07-11
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多