Search code examples
pythonjsondictionaryrecursionnested-loops

Update Nested Dictionary value using Recursion


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
      }

Solution

  • 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}],
    }