admin管理员组文章数量:1252717
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.)
本文标签: pythonNest dictionaries within a list into respective dictionariesStack Overflow
版权声明:本文标题:python - Nest dictionaries within a list into respective dictionaries - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740319725a2261009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论