我有本字典:
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'}
}但这并不是我所期望的。如何消除重复?我怎么纠正它呢?
发布于 2017-07-13 15:36:57
你可以简单地创建一个带有理解的新字典:
>>> {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)发布于 2017-07-13 15:40:09
就快到了
for key in my_dict:
... my_dict[key]={key:my_dict.get(key)}https://stackoverflow.com/questions/45074234
复制相似问题