[Python] Transform list of dictionaries into nested dictionary

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following list of dictionaries

    l = [{'u': 1, 'v': 2, 'k': [1, 1, 1, 1, 1]},
    {'u': 1, 'v': 3, 'k': [2, 2, 2, 2, 2]},
    {'u': 2, 'v': 3, 'k': [3, 3, 3, 3, 3]},
    {'u': 1, 'v': 4, 'k': [4, 4, 4, 4, 4]},
    {'u': 2, 'v': 5, 'k': [5, 5, 5, 5, 5]}]


    I want to created a nested dictionary of this:

    nested_d = {
    '1': {'2': [1, 1, 1, 1, 1],
    '3': [2, 2, 2, 2, 2],
    '4': [4, 4, 4, 4, 4]},
    '2': {'3': [3, 3, 3, 3, 3],
    '5': [5, 5, 5, 5, 5]}
    }


    How can I achieve this easily (without a for loop / in a one-liner)?

    Continue reading...

Compartilhe esta Página