[Python] how to "zip" two nested dictionaries

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I have a nested dict with different levels of nesting

    dict1 = {
    'A': {'a': 1},
    'B': 2,
    'C': {'c': 3},
    'D': {'d': {'dd': 4}}
    }


    I want to perform (for instance) key-wise multiplication. With flat dict this is straightforward:

    {k: v * 2 for k, v in dict.items()}


    How can I do the same in the above dict?

    A follow-up question is processing a pair of nested dicts with partial key overlap.

    dict2 = {
    'A': {'a': 1},
    'D': {'d': {'dd': 4}}
    }


    A key-wise addition of flat dicts is straightforward:

    {k: dict1[k] + dict2[k] for k, v in dict2.items()}


    How can I do the same with nested dicts?

    Continue reading...

Compartilhe esta Página