How to update value of unique key in nested dictionary?

Viewed 114

Let's say that we have this dict:

{
  "app_url": "",
  "models": [
    {
      "perms": {
        "add": true,
        "change": true,
        "delete": true
      },
      "add_url": "/admin/cms/news/add/",
      "admin_url": "/admin/cms/news/",
      "name1": ""
    }
  ],
  "has_module_perms": true,
  "name2": "u\u0027CMS\u0027"
}

How to set a new value for the key add_url if the requirement is to only provide the key and the value?

So i don't want to do something like data["models"]["add_url"] = value but instead i'd like to pass only "add_url" and the new value to a function.

In my case every key in the dict is a unique str so that it can't happen that a key appears more then once.

1 Answers

You can use a recursive function to find the field and update the value.

your_dict = {
  "app_url": "",
  "models": [
    {
      "perms": {
        "add": True,
        "change": True,
        "delete": True
      },
      "add_url": "/admin/cms/news/add/",
      "admin_url": "/admin/cms/news/",
      "name1": ""
    }
  ],
  "has_module_perms": True,
  "name2": "u\u0027CMS\u0027"
}

def recursive_update(haystack, needle, value):
  if isinstance(haystack, dict):
    for key, value_dict in haystack.items():
      if needle == key:
        haystack[key] = value
      elif isinstance(value_dict, list) or isinstance(value_dict, dict):
          recursive_update(value_dict, needle, value)
  elif isinstance(haystack, list):
    for value_list in haystack:
      if isinstance(value_list, dict):
        recursive_update(value_list, needle, value)

  return haystack

Usage:

recursive_update(your_dict, 'add_url', 'http://www.google.com')

Note: I don't recommend you using an implicit approach towards programming.

The above is not thoroughly tested, so make sure to test it out; it's more of an example of how recursion can work towards achieving your goal.

Related