I am having a saved list of Python dict keys:
['level_one', 'level_two', 'test']
These are the keys of a dictionary:
mydict = {
'level_one' : {
'level_two' : {
'test' : "Hello World"
}
}
}
Normally I could set the test
key like this:
mydict['level_one']['level_two']['test'] = "Hello StackOverflow"
Unfortunately, the list/dict are generated on the fly, and I don't know how deep it can go. Is there a possibility to update the dict key by the list of keys without using braces?
I only was able to reflect this functionality for getting the string:
def deepGet(sourceDict, *keys):
return reduce(lambda d, k: d.get(k) if d else None, keys, sourceDict)
> deepGet(mydict, *['level_one', 'level_two', 'test'])
>> Hello World
Not a duplicate. This is regarding setting, not getting of nested dictionary.