【发布时间】:2017-12-17 20:36:41
【问题描述】:
我有一本字典:
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={}移到循环下方即可。
标签: python python-2.7 python-3.x dictionary