[Python] Update value of a nested dictionary of varying depth

Discussão em 'Python' iniciado por Stack, Dezembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA

    dictionary1 = {
    "level1": {
    "level2": {"levelA": 0, "levelB": 1}
    }
    }
    update = {
    "level1": {
    "level2": {"levelB": 10}
    }
    }
    dictionary1.update(update)
    print(dictionary1)


    {
    "level1": {
    "level2": {"levelB": 10}
    }
    }


    I know that update deletes the values in level2 because it's updating the lowest key level1.

    How could I tackle this, given that dictionary1 and update can have any length?

    Continue reading...

Compartilhe esta Página