Reputation: 74
I would like to update or create a nested dictionary without altering the existing content.
In the example below I will try to add the couple {'key2.2': 'value2.2'}
nested as a child to the entry key2.
mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
mydict['key2'].update({'key2.2': 'value2.2'})
pprint(mydict)
{'key1': 'value1', 'key2': {'key2.1': 'value2.1', 'key2.2': 'value2.2'}}
This is what I expected, no problem here.
mydict = {'key1': 'value1'}
mydict['key2'].update({'key2.2': 'value2.2'})
KeyError: 'key2'
Seems logic, so let's try something else..
mydict = {'key1': 'value1'}
mydict.update({'key2': {'key2.2': 'value2.2'}})
pprint(mydict)
{'key1': 'value1', 'key2': {'key2.2': 'value2.2'}}
Perfect ! Let's check if this works with case 1 too.
mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
mydict.update({'key2': {'key2.2': 'value2.2'}})
pprint(mydict)
{'key1': 'value1', 'key2': {'key2.2': 'value2.2'}}
The existing entry {'key2.1': 'value2.1'}
got deleted, this is not what I want.
What would be the best way to achieve what I want ? Like a nested update ? I know this would be possible with a couple of try:/except KeyError:, but it doesn't seems very clean.
Upvotes: 0
Views: 62
Reputation: 1168
Code:
mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
mydict['key2.2'.split('.')[0]].update({'key2.2' : 'value2.2'})
print(mydict)
Output:
{'key2': {'key2.2': 'value2.2', 'key2.1': 'value2.1'}, 'key1': 'value1'}
Upvotes: 0
Reputation: 9494
Try:
mydict = {'key1': 'value1', 'key2': {'key2.1': 'value2.1'}}
if "key2" in mydict:
mydict["key2"].update({'key2.2': 'value2.2'})
else:
mydict["key2"] = {'key2.2': 'value2.2'}
Upvotes: 0
Reputation: 1358
You could use defaultdict:
from collections import defaultdict
mydict = defaultdict(dict)
mydict.update({'key1': 'value1', 'key2': {'key2.1': 'value2.1'}})
mydict['key2'].update({'key2.2': 'value2.2'})
print(mydict)
mydict = defaultdict(dict)
mydict.update({'key1': 'value1'})
mydict['key2'].update({'key2.2': 'value2.2'})
print(mydict)
Outputs:
defaultdict(<class 'dict'>, {'key1': 'value1', 'key2': {'key2.1': 'value2.1', 'key2.2': 'value2.2'}})
defaultdict(<class 'dict'>, {'key1': 'value1', 'key2': {'key2.2': 'value2.2'}})
Upvotes: 3