Search code examples
pythonlistloopsdictionary

Nest dictionaries within a list into respective dictionaries


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


Solution

  • You can use a list comprehension that outputs a new dict for each key-value pair:

    [{key: value} for key, value in zip(outer_list, animal_list)]
    

    Demo: https://ideone.com/IDUJL8

    Also, if it is truly guaranteed that outer_list always contains the same value throughout, you can simply extract the first item as a fixed key instead:

    key = outer_list[0]
    [{key: animal} for animal in animal_list]