【问题标题】:Add a new dict to a existing dictionary as a value to the key [duplicate]将新字典添加到现有字典作为键的值[重复]
【发布时间】: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


【解决方案1】:

你可以简单地创建一个带有理解的新字典:

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

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

正如 @AshwiniChaudhary 在 cmets 中提到的,您可以简单地将 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)

【讨论】:

  • 感谢您的建议!
【解决方案2】:

差不多了

for key in my_dict:
...     my_dict[key]={key:my_dict.get(key)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2018-09-22
    • 1970-01-01
    • 2019-11-21
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多