Updating nested dictionaries when data has existing key

前端 未结 5 708
感动是毒
感动是毒 2020-12-08 22:22

I am trying to update values in a nested dictionary, without over-writting previous entries when the key already exists. For example, I have a dictionary:

           


        
5条回答
  •  既然无缘
    2020-12-08 23:26

    This is a very nice general solution to dealing with nested dicts:

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

    That allows nested keys to be set at any level:

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

    For a single level of nesting, defaultdict can be used directly:

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

    And here's a way using only dict:

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

提交回复
热议问题