How would you modify/create keys/values in a dict of nested dicts based on the values of a list, in which the last item of the list is a value for the dict, and the rest of items reefer to keys within dicts? This would be the list:
list_adddress = [ "key1", "key1.2", "key1.2.1", "value" ]
This would only be a problem in situations like when parsing command line arguments. It's obvious that modifying/creating this value within a script would be pretty easy using dict_nested["key1"]["key1.2"]["key1.2.1"]["value"]
.
This would be a nested dict of dicts:
dict_nested = {
"key1": {
"key1.1": {
"...": "...",
},
"key1.2": {
"key1.2.1": "change_this",
},
},
"key2": {
"...": "..."
},
}
I guess that in this case, something like a recursive function or a list comprehension would be required.
def ValueModify(list_address, dict_nested):
...
...
ValueModify(..., ...)
Also, if items in list_address
would reefer to keys in non-existing dictionaries, they should be created.
One-liner:
Note:
dict.get
andoperator.getitem
would produce wrong exceptions here.An explicit for-loop as in Joel Cornett's answer might be more readable.
If you want to create non-existing intermediate dictionaries:
If you want to override existing intermediate values that are not dictionaries e.g., strings, integers:
Example
Tests
I think this works like you're after.
I'm using
isinstance
, which is type checking, and not generally something you do in Python, but it does set the value as expected.-- Edited --
Added in the missing key check to set nested values if the original
nested_dict
is not fully populated.Here's a recursive solution.
To insert a new key-value pair or update the value of a pair:
test: