Update nested dictionaries when data has an existing key

I am trying to update values ​​in a nested dictionary without overwriting 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 add "myKey" with new values ​​without overwriting the previous ones?

+5
source share
3 answers

Try something like this:

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

This template will add a key to an existing nested dictionary or create a new nested dictionary if it does not exist.

+5
source

You can use collections.defaultdict for this and just set the key-value pairs inside the nested dictionary.

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

Alternatively, you can also write these last two lines as

 my_dict['myKey'].update({"nestedDictKey1" : a_value }) my_dict['myKey'].update({"nestedDictKey2" : another_value }) 
+5
source
 myDict["myKey"]["nestedDictKey2"] = anotherValue 

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

Example:

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

Source: https://habr.com/ru/post/1207632/


All Articles