3

I have two dictionaries that I'm trying to perform a union based on a key within the "dta" dictionary.

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"
}

And I would like to do a union on the "schema" key of dta. However when I try this

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

This is my result

{
    "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",
}

However, I'm trying to get this as my result

{
    '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'
            }
        }
    }
}

Is there a way to do a union using a key as the starting place?

daniboy000
  • 1,069
  • 2
  • 16
  • 26
SpindriftSeltzer
  • 322
  • 3
  • 12

1 Answers1

4

You're merging other_data with the top-level dta dictionary. You should be merging it with dta['detailType']['payload-info']['schema']. So use:

if "detailType" in dta:
    dta['detailType']['payload-info']['schema'].update(other_data)
Barmar
  • 741,623
  • 53
  • 500
  • 612