我有一本字典:到現有的字典中添加新字典的價值,關鍵
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'}
}
但是不是我的預期。如何消除重複? 我如何解決問題?
你一遍又一遍地重複使用相同的字典。如果你不想分享它,或者更好的話,創建一個副本**在循環**中創建一個新的字典。 –
只需在循環下移動'new_value_for_dict = {}'。 –
感謝您的幫助 –