[Python] Transform 2-level nested dictonary to list of dictionaries [duplicate]

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

  1. Stack

    Stack Membro Participativo

    I have the following nested dictionary:

    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]}
    }


    I want to "flatten" this dictionary and obtain the following output:

    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]}]


    Ideally, I would like to use itertools. The following code works but I would like to know if there is room for improvement.

    from itertools import chain

    l = chain.from_iterable([[
    {'u': u,
    'v': v,
    'k': d[v]
    } for v in d.keys()
    ] for u in d.keys()

    ])


    Please advice

    Continue reading...

Compartilhe esta Página