我有一本看起来像这样的字典:
dict1 = {'Store_1': {},
'Store_2': {}}
我有一个要放入store1和store2的词典列表。
[{'Apple': '726',
'Pear': '777',
'Orange': '1.004',
'Pineapple': '696',
'melon': '828'},
{'orange': '650',
'melon': '654',
'avocado': '657',
'pear': '645',
'apple': '647',
'berries': '655'}]
所需的输出将是:
dict1 = {'Store_1': {'Apple': '726', 'Pear': '777', 'Orange': '1.004', ...}, 'Store_2': {'orange': '650', 'melon': '654', ...}}
我该如何实现?
谢谢
答案 0 :(得分:1)
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'}}
此方法的工作方式是循环遍历列表的长度,对于每次迭代,首先获取列表中的值,然后在字典中使用该数字的名称(使用.format
)创建一个键