Updating nested dictionaries when data has existing key

前端 未结 5 716
感动是毒
感动是毒 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条回答
  •  猫巷女王i
    2020-12-08 23:01

    myDict["myKey"]["nestedDictKey2"] = anotherValue
    

    myDict["myKey"] returns the nested dictionary to which we can add another key like we do for any dictionary :)

    Example:

    >>> d = {'myKey' : {'k1' : 'v1'}}
    >>> d['myKey']['k2'] = 'v2'
    >>> d
    {'myKey': {'k2': 'v2', 'k1': 'v1'}}
    

提交回复
热议问题