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:
myDict = {}
myDict["myKey"] = { "nestedDictKey1" : aValue }
giving,
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue }}
Now, I want to add another entry , under "myKey"
myDict["myKey"] = { "nestedDictKey2" : anotherValue }}
This will return:
print myDict
>> { "myKey" : { "nestedDictKey2" : anotherValue }}
But I want:
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue ,
"nestedDictKey2" : anotherValue }}
Is there a way to update or append "myKey"
with new values, without overwriting the previous ones?
You could treat the nested dict as immutable:
myDict["myKey"] = dict(myDict["myKey"], **{ "nestedDictKey2" : anotherValue })
This is a very nice general solution to dealing with nested dicts:
That allows nested keys to be set at any level:
For a single level of nesting,
defaultdict
can be used directly:And here's a way using only
dict
:myDict["myKey"]
returns the nested dictionary to which we can add another key like we do for any dictionary :)Example:
You can use
collections.defaultdict
for this, and just set the key-value pairs within the nested dictionary.Alternatively, you can also write those last 2 lines as