最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Nest dictionaries within a list into respective dictionaries - Stack Overflow

programmeradmin2浏览0评论

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 0
Add a comment  | 

2 Answers 2

Reset to default 4

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/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.)

发布评论

评论列表(0)

  1. 暂无评论