Home > Software design >  Is there a way to add values from one key in a dictionary to the values of the same key in another d
Is there a way to add values from one key in a dictionary to the values of the same key in another d

Time:10-27

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.

CodePudding user response:

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": "",
    },
}
  • Related