[英]Adding a dictionary inside a dictionary for loop
I have a dictionary which looks like this:我有一本看起来像这样的字典:
dict1 = {'Store_1': {},
'Store_2': {}}
And I have a list of dictionaries which I would like to put into store1 and store 2.我有一个字典列表,我想将它们放入 store1 和 store 2 中。
[{'Apple': '726',
'Pear': '777',
'Orange': '1.004',
'Pineapple': '696',
'melon': '828'},
{'orange': '650',
'melon': '654',
'avocado': '657',
'pear': '645',
'apple': '647',
'berries': '655'}]
The desired output would be:所需的 output 将是:
dict1 = {'Store_1': {'Apple': '726', 'Pear': '777', 'Orange': '1.004', ...}, 'Store_2': {'orange': '650', 'melon': '654', ...}}
How can I achieve this?我怎样才能做到这一点?
Thank you谢谢
l=[{'Apple': '726',
'Pear': '777',
'Orange': '1.004',
'Pineapple': '696',
'melon': '828'},
{'orange': '650',
'melon': '654',
'avocado': '657',
'pear': '645',
'apple': '647',
'berries': '655'}]
Dict1={}
for x in range(len(l)):
Dict1['Store_{}'.format(x+1)]=l[x]
print(Dict1)
>>> {'Store_1': {'Apple': '726', 'Pear': '777', 'Orange': '1.004', 'Pineapple': '696', 'melon': '828'}, 'Store_2': {'orange': '650', 'melon': '654', 'avocado': '657', 'pear': '645', 'apple': '647', 'berries': '655'}}
The way this works is by looping through the length of the list, and for each iteration first taking the value in the list, then creating a key in the dictionary (using .format
)with the name of that number.它的工作方式是循环遍历列表的长度,对于每次迭代,首先获取列表中的值,然后在字典中创建一个键(使用
.format
),其中包含该数字的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.