1

There is a nested dictionary with multiple level of keys. The requirements are:

  • Create nested keys by using keypath if it doesn't exist
  • Update the value by using the keypath if it exists

For example, this is the dictionary:

{
    "animal": {
        "dog": {
            "type": "beagle"
        }
    },
    "man": {
        "name": "john",
        "age": 36
    },
    "plant": {
        "fruit": {
            "apple": {
                "type": "gala"
            }
        }
    }
}

Here are the functions to update the value or append a new nested keypath:

appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)

Here is the expected result:

{
    "animal": {
        "dog": {
            "type": "beagle"
        }
    },
    "man": {
        "name": "daniel",
        "age": 36
    },
    "plant": {
        "fruit": {
            "apple": {
                "type": "gala"
            }
        }
    },
    "computer": {
        "laptop": {
            "maker": "hp"
        }
    }    
}

My question is how to implement the appendDict() function in order to support the requirements?

Here is my code so far which doesn't work yet:

json_dict = {    
    "animal": {"dog": {"type": "beagle"}},
    "man": {"name": "john", "age": 36},
    "plant": {"fruit": {"apple": {"type": "gala"}}}
}

def appendDict(keys, value, json_dict):
    for index, key in enumerate(keys):
        if key not in json_dict:
            if index == len(keys) - 1:
                some_data = {}
                some_data[key] = value
                json_dict[key] = some_data
            else:
                some_data = {}
                json_dict[key] = some_data
        else:
            json_dict[key] = value
            
appendDict(["man", "name"], "daniel", json_dict)            
appendDict(["computer", "laptop", "maker"], "hp", json_dict)
2
  • Seems like a good candidate for a while loop or some recursion. Is this homework? What's your question here? Commented Mar 23, 2021 at 20:03
  • Updated: added the question. Need to implement the function to support the requirements. Commented Mar 23, 2021 at 20:11

1 Answer 1

1

You can use recursion by slicing keys at every call:

def appendDict(keys, value, json_dict):
   if len(keys) == 1:
      json_dict[keys[0]] = value
   else:
      if keys[0] not in json_dict:
         json_dict[keys[0]] = {}
      appendDict(keys[1:], value, json_dict[keys[0]])

json_dict = {'animal': {'dog': {'type': 'beagle'}}, 'man': {'name': 'john', 'age': 36}, 'plant': {'fruit': {'apple': {'type': 'gala'}}}}
appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)

import json
print(json.dumps(json_dict, indent=4))

Output:

{
  "animal": {
     "dog": {
        "type": "beagle"
     }
  },
  "man": {
     "name": "daniel",
     "age": 36
   },
   "plant": {
       "fruit": {
          "apple": {
              "type": "gala"
           }
       }
    },
    "computer": {
        "laptop": {
          "maker": "hp"
       }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.