我有一本字典:
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'}
}
但不是我的预期。如何消除重复? 我该如何纠正?
答案 0 :(得分:4)
您可以简单地创建一个具有理解力的新词典:
>>> {k:{k:v} for k,v in my_dict.items()}
{'sesame': {'sesame': '45'}, 'vegetables': {'vegetables': '30'}, 'papaya': {'papaya': '18'}, 'apples': {'apples': '21'}}
但是,我认为没有任何理由这样做。您没有获得更多信息,但迭代dict值或检索信息变得更加困难。
正如@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)
答案 1 :(得分:2)
for key in my_dict:
... my_dict[key]={key:my_dict.get(key)}