简体   繁体   中英

Generic Function to replace value of a key in a dict or nested dict or list of dicts

So i have a Dict like so:

{
  "environment": [
    {
      "appliances": [
        {
          "services-status": "GOOD",
          "ping-status": "REACHABLE"
        },
        {
          "softwareVersion": "16.1-R1-S2 50b46b5 20170829",
          "services-status": "GOOD",
          "ping-status": "REACHABLE"
        }
      ],
      "vd_url": "https://bla1"
    },
    {
      "appliances": [
        {
          "ipAddress": "10.4.64.108"
          "type": "branch",
          "sync-status": "IN_SYNC"
        },
        {
          "services-status": "GOOD",
          "ping-status": "REACHABLE"
          "sync-status": "IN_SYNC"
        }
      ],
      "vd_url": "https://bla2"
    },
  ],
  "failed_urls": [
    "https://gslburl",
    "https://gslburl",
    "https://localhost",
    "https://localhost",
    "https://localhost"
  ]
}

or it can be something like this

{
  "softwareVersion": "16.1-R1-S2 50b46b5 20170829",
  "services-status": "GOOD",
  "ping-status": "REACHABLE"
  "vd_url" : "https://blah3"
}

or it can be something like this

{
  "environment": [
    {
      "appliances": [
        {
          "services-status": "GOOD",
          "ping-status": "REACHABLE"
        },
        {
          "softwareVersion": "16.1-R1-S2 50b46b5 20170829",
          "services-status": "GOOD",
          "ping-status": "REACHABLE"
        }
      ],
      "vd_url": "https://bla1"
    }
  ]
}

or it can be in any combination of dictionaries possible, but what i am trying to achieve is write a generic function that can take the dictionary, replace a key with another value and return the new dict. Just a pseudo code:

def replace(dict_obj, key, new_value)
    for dict in dict_obj:
        for k, v in dict.items()
        if k == key:
              dict[k] = new_value

    return dict_obj

but in the end i want the same dictionary object - dict_obj that i passed but with the new values and it should work for any type of dicts above Scratching my head as to how to solve it :(

You can use recursion to determine if value from a key,value pair is a list or a dict and then iterate accordingly.

def replace(dict_obj, key, new_value):
    for k,v in dict_obj.iteritems():
        if isinstance(v,dict):
            # replace key in dict
            replace(v, key, new_value)
        if isinstance(v,list):
            # iterate through list
            for item in v:
                if isinstance(item,dict):
                    replace(item, key, new_value)
        if k == key:
            dict_obj[k] = new_value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM