[Python] Nest dictionaries within a list into respective dictionaries

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have two lists, animal_list and outer_list. animal_list contains dictionaries within the list. outer_list is just a simple list with exact same elements

    animal_list = [{'animal': 'dog', 'color': 'black'},
    {'animal': 'cat', 'color': 'brown'}]

    outer_list = ['pet', 'pet']


    How can I combine the two lists to make a nested dictionary within a single list without overwriting each record since the outer key (outer_list) is the exact same. My desired state below

    [
    {'pet':{'animal': 'dog', 'color': 'black'}},
    {'pet':{'animal': 'cat', 'color': 'brown'}}
    ]


    I've tried the following but it just writes the last value since the outer key 'pet' is the same

    attempt_list = []
    attempt_list.append(dict(zip(outer_list,animal_list)))

    Failed output below
    [{'pet': {'animal': 'cat', 'color': 'brown'}}]


    I imagine a loop is needed but can't for the life of me figure it out

    Continue reading...

Compartilhe esta Página