2017-07-13 60 views
1

我有一本字典:到現有的字典中添加新字典的價值,關鍵

my_dict = { 
    "apples":"21", 
    "vegetables":"30", 
    "sesame":"45", 
    "papaya":"18", 
} 

我要生成一個新的,將是這樣的:

my_dict = { 
    "apples" : {"apples":"21"}, 
    "vegetables" : {"vegetables":"30"}, 
    "sesame" : {"sesame":"45"}, 
    "papaya" : {"papaya":"18"}, 
} 

我寫這樣的代碼....

my_dict = { 
    "apples":"21", 
    "vegetables":"30", 
    "sesame":"45", 
    "papaya":"18", 
} 

new_dict={} 
new_value_for_dict={} 

for key in my_dict: 
    new_value_for_dict[key]= my_dict[key] 
    new_dict[key]= new_value_for_dict 
    # need to clear the last key,value of the "new_value_for_dict" 

print(new_dict) 

和輸出當屬此:

{'vegitables':{'vegitables': '30', 'saseme': '45', 
       'apples': '21','papaya': '18'}, 
'saseme':{'vegitables': '30', 'saseme': '45', 
      'apples': '21', 'papaya': '18'}, 
'apples': {'vegitables': '30', 'saseme': '45', 
      'apples': '21', 'papaya': '18'}, 
'papaya': {'vegitables': '30', 'saseme': '45', 
      'apples': '21', 'papaya': '18'} 
} 

但是不是我的預期。如何消除重複? 我如何解決問題?

+1

你一遍又一遍地重複使用相同的字典。如果你不想分享它,或者更好的話,創建一個副本**在循環**中創建一個新的字典。 –

+0

只需在循環下移動'new_value_for_dict = {}'。 –

+0

感謝您的幫助 –

回答

4

你可以簡單地創建一個新的字典與理解:

>>> {k:{k:v} for k,v in my_dict.items()} 
{'sesame': {'sesame': '45'}, 'vegetables': {'vegetables': '30'}, 'papaya': {'papaya': '18'}, 'apples': {'apples': '21'}} 

我看不出有任何理由這樣做,雖然。您不會獲得更多信息,但迭代字典值或檢索信息會變得更加困難。

正如意見中提到的@AshwiniChaudhary,你可以簡單地移動new_value_for_dict={}內循環,以重建在每次迭代一個新的內部字典:

my_dict = { 
    "apples":"21", 
    "vegetables":"30", 
    "sesame":"45", 
    "papaya":"18", 
} 

new_dict={} 

for key in my_dict: 
    new_value_for_dict={} 
    new_value_for_dict[key]= my_dict[key] 
    new_dict[key]= new_value_for_dict 

print(new_dict) 
+0

謝謝您的建議! –

1

幾乎沒有

for key in my_dict: 
...  my_dict[key]={key:my_dict.get(key)}