簡體   English   中英

在循環字典中添加字典

[英]Adding a dictionary inside a dictionary for loop

我有一本看起來像這樣的字典:

dict1 = {'Store_1': {},
 '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'}]

所需的 output 將是:

dict1 = {'Store_1': {'Apple': '726', 'Pear': '777', 'Orange': '1.004', ...}, 'Store_2': {'orange': '650', 'melon': '654', ...}}

我怎樣才能做到這一點?

謝謝

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 ),其中包含該數字的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM