当数据具有现有键时更新嵌套字典

新手上路,请多包涵

我正在尝试更新嵌套字典中的值,而不会在键已经存在时覆盖以前的条目。例如,我有一本字典:

   myDict = {}
  myDict["myKey"] = { "nestedDictKey1" : aValue }

给予,

  print myDict
>> { "myKey" : { "nestedDictKey1" : aValue }}

现在,我想在 "myKey" 下添加另一个条目

myDict["myKey"] = { "nestedDictKey2" : anotherValue }}

这将返回:

 print myDict
>> { "myKey" : { "nestedDictKey2" : anotherValue }}

但是我想要:

 print myDict
>> { "myKey" : { "nestedDictKey1" : aValue ,
                 "nestedDictKey2" : anotherValue }}

有没有办法更新或附加 "myKey" 新值,而不覆盖以前的值?

原文由 eric 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 470
2 个回答

这是 处理嵌套字典的一个非常好的通用解决方案

 import collections
def makehash():
    return collections.defaultdict(makehash)

这允许在任何级别设置嵌套键:

 myDict = makehash()
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]["nestedDictKey3"]["furtherNestedDictKey"] = aThirdValue

对于单层嵌套,可以直接使用 defaultdict

 from collections import defaultdict
myDict = defaultdict(dict)
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue

这是一种仅使用 dict 的方法:

 try:
  myDict["myKey"]["nestedDictKey2"] = anotherValue
except KeyError:
  myDict["myKey"] = {"nestedDictKey2": anotherValue}

原文由 Allen Luce 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以为此使用 collections.defaultdict ,并在嵌套字典中设置键值对。

 from collections import defaultdict
my_dict = defaultdict(dict)
my_dict['myKey']['nestedDictKey1'] = a_value
my_dict['myKey']['nestedDictKey2'] = another_value

或者,您也可以将最后两行写为

my_dict['myKey'].update({"nestedDictKey1" : a_value })
my_dict['myKey'].update({"nestedDictKey2" : another_value })

原文由 Stuart 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏