Search code examples
pythondictionarydictionary-comprehension

Iterate through a dictionary provided keys are from a list


Consider I have a list and dictionary like

list = ['master', 'sub1', 'sub2']
dict={'master':{'sub1':{'sub2':5}}}

Is there a way to iterate through a nested dictionary to get so that I can update the value stored there?

dict['master']['sub1']['sub2'] = new_value

The list of keys and new_value can vary so the solution can't be static, is there a solution to such a problem?

Using the functools.reduce() we can get the specific value stored within that hierarchy but I'm not quite sure how to change the value stored within that hierarchy

Thanks for the help!


Solution

  • You can use recursion:

    l = ['master', 'sub1', 'sub2']
    d = {'master':{'sub1':{'sub2':5}}}
    def to_dict(l, val=5):
      return {l[0]:val if not l[1:] else to_dict(l[1:])}
    
    print(to_dict(l))
    

    Output:

    {'master': {'sub1': {'sub2': 5}}}