关于python:将新的dict添加到现有字典中作为键的值

Add a new dict to a existing dictionary as a value to the key

本问题已经有最佳答案,请猛点这里访问。

我有一本字典:

1
2
3
4
5
6
my_dict = {
   "apples":"21",
   "vegetables":"30",
   "sesame":"45",
   "papaya":"18",
}

我想生成一个新的,看起来像这样:

1
2
3
4
5
6
my_dict = {
   "apples" : {"apples":"21"},
   "vegetables" : {"vegetables":"30"},
   "sesame" : {"sesame":"45"},
   "papaya" : {"papaya":"18"},
}

我写了这样的代码……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)

输出结果如下:

1
2
3
4
5
6
7
8
9
{'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'}
}

但这不是我所期望的。如何消除重复?我如何纠正它?


您可以简单地创建一个理解力强的新dict:

1
2
>>> {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={},以便在每次迭代中重新创建一个新的内部dict:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)}