python - 将新字典添加到现有字典中作为键的值

标签 python python-2.7 python-3.x dictionary

<分区>

我有一本字典:

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'}
}

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

最佳答案

您可以简单地创建一个具有理解力的新字典:

>>> {k:{k:v} for k,v in my_dict.items()}
{'sesame': {'sesame': '45'}, 'vegetables': {'vegetables': '30'}, 'papaya': {'papaya': '18'}, 'apples': {'apples': '21'}}

不过,我看不出有任何理由这样做。您不会获得更多信息,但迭代字典值或检索信息变得更加困难。

正如@AshwiniChaudhary 在评论中提到的,您可以简单地将 new_value_for_dict={} 移动到循环内,以便在每次迭代时重新创建一个新的 inner-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)

关于python - 将新字典添加到现有字典中作为键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45074234/

相关文章:

Python raw_input 不接受输入

python - Matplotlib 显示页面上的滚动条

python - 使用网络抓取工具时,如何确保抓取第一页后,它会抓取第二页?

python - 解释(和比较)numpy.correlate 的输出

python - VIM - 未知功能 : pythoncomplete#Complete

python - 如何根据索引而不是值编写 numpy where 条件?

python - 如何从 SQLAlchemy ORM 类生成列值的字典?

python - Multiprocessing Pool 非阻塞检测完成的任务

python - python 3.6 subprocess.Popen().returncode of 100 是什么意思?

python - 排序功能。解释