Is there a way to add values from one key in a dictionary to the values of the same key in another dictionary?

Question:

i have one dict structured like this:

d1 = {'837729451428151376': {'Username': 'CatCam', 'Mana': 3, 'HP': 10000, 'Location': 'Crossroads', 'SC': 10, 'Rage': 0, 'InitManaDate': 1666875873, 'NextMana': 1666875873, 'ReadyInventory': 'n        goodiebag', 'EquippedInventory': ' ', 'ReadyDate': 1666818273, 'Lastactiontime': 1666818273, 'Lastaction': 'start', 'Nextaction': ''}, '990432921292795934': {'Username': 'Vmidafk', 'Mana': 3, 'HP': 10000, 'Location': 'Crossroads', 'SC': 10, 'Rage': 0, 'InitManaDate': 1666875873, 'NextMana': 1666875873, 'ReadyInventory': 'n        goodiebag', 'EquippedInventory': ' ', 'ReadyDate': 1666818273, 'Lastactiontime': 1666818273, 'Lastaction': 'start', 'Nextaction': ''}}

and a second one structured like this:

d2 = {'837729451428151376': {'SC': 2}, '990432921292795934': {'SC': 4}}}

how can I add the SC values from d2 onto the SC values of d1 without losing or changing other keys and values in d1?

I tried manually rewriting the d2 values to 10+ their current value and then using:


d3 = d1 | d2 

but that just overwrote the d1 values for SC and removed all keys other than SC under the ID# in the new dictionary.

Asked By: plerpsandplerps

||

Answers:

Try:

for k, v in d2.items():
    if k in d1:
        d1[k]["SC"] = v["SC"]

print(d1)

Prints:

{
    "837729451428151376": {
        "Username": "CatCam",
        "Mana": 3,
        "HP": 10000,
        "Location": "Crossroads",
        "SC": 2,
        "Rage": 0,
        "InitManaDate": 1666875873,
        "NextMana": 1666875873,
        "ReadyInventory": "n        goodiebag",
        "EquippedInventory": " ",
        "ReadyDate": 1666818273,
        "Lastactiontime": 1666818273,
        "Lastaction": "start",
        "Nextaction": "",
    },
    "990432921292795934": {
        "Username": "Vmidafk",
        "Mana": 3,
        "HP": 10000,
        "Location": "Crossroads",
        "SC": 4,
        "Rage": 0,
        "InitManaDate": 1666875873,
        "NextMana": 1666875873,
        "ReadyInventory": "n        goodiebag",
        "EquippedInventory": " ",
        "ReadyDate": 1666818273,
        "Lastactiontime": 1666818273,
        "Lastaction": "start",
        "Nextaction": "",
    },
}
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.