Home > Enterprise >  Update Nested Dictionary value using Recursion
Update Nested Dictionary value using Recursion

Time:07-24

I want to update Dict dictionary's value by inp dictionary's values using recursion or loop. also the format should not change mean use recursion or loop on same format please suggest a solution that is applicable to all level nesting not for this particular case

dict={
           "name": "john",
           "quality":
                       {
                         "type1":"honest",
                         "type2":"clever"
                      },
         "marks":
                 [
                     {
                          "english":34
                     },
                     {
                          "math":90
                     }
                ]
          }
inp = {
          "name" : "jack",
          "type1" : "dumb",
          "type2" : "liar",
          "english" : 28,
          "math" : 89
      }

CodePudding user response:

First, make sure you change the name of the first Dictionary, say to myDict, since dict is reserved in Python as a Class Type.

The below function will do what you are looking for, in a recursive manner.

def recursive_swipe(input_var, updates):
    if isinstance(input_var, list):
        output_var = []
        for entry in input_var:
            output_var.append(recursive_swipe(entry, updates))
    elif isinstance(input_var, dict):
        output_var = {}
        for label in input_var:
            if isinstance(input_var[label], list) or isinstance(input_var[label], dict):
                output_var[label] = recursive_swipe(input_var[label], updates)
            else:
                if label in updates:
                    output_var[label] = updates[label]
    else:
        output_var = input_var
    return output_var


myDict = recursive_swipe(myDict, inp)

You may look for more optimal solutions if there are some limits to the formatting of the two dictionaries that were not stated in your question.

CodePudding user response:

Another solution, changing the dict in-place:

dct = {
    "name": "john",
    "quality": {"type1": "honest", "type2": "clever"},
    "marks": [{"english": 34}, {"math": 90}],
}

inp = {
    "name": "jack",
    "type1": "dumb",
    "type2": "liar",
    "english": 28,
    "math": 89,
}


def change(d, inp):
    if isinstance(d, list):
        for i in d:
            change(i, inp)
    elif isinstance(d, dict):
        for k, v in d.items():
            if not isinstance(v, (list, dict)):
                d[k] = inp.get(k, v)
            else:
                change(v, inp)


change(dct, inp)
print(dct)

Prints:

{
    "name": "jack",
    "quality": {"type1": "dumb", "type2": "liar"},
    "marks": [{"english": 28}, {"math": 89}],
}
  • Related