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
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
Share Improve this question edited Feb 14 at 1:30 qwerty12 asked Feb 14 at 0:58 qwerty12qwerty12 555 bronze badges 02 Answers
Reset to default 4You 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/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]
Wrapping each pair so we can apply dict
to each:
attempt_list = list(map(dict,zip(zip(outer_list,animal_list))))
Attempt This Online!
(But I just did this because you tried dict(zip
and as a fun little challenge. I prefer @blhsing's list comp.)