Change values in dict of nested dicts using items in a list?

Viewed 7071

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.

5 Answers
Related