通用函数替换字典或嵌套字典或字典列表中键的值

时间:2018-03-28 03:48:24

标签: python python-2.7 dictionary

所以我有这样的Dict:

1,137,481,704 --- 4,253,864

或者它可以是这样的

{
  "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"
  ]
}

或者它可以是这样的

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

或者它可以是字典的任意组合,但我想要实现的是写一个可以取字典的泛型函数, 用另一个值替换一个键并返回新的dict。 只是一个伪代码:

{
  "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"
    }
  ]
}

但最后我想要相同的字典对象 - 我传递的dict_obj但是使用了新值,它应该适用于上面任何类型的dicts 抓住我的头脑如何解决它:(

1 个答案:

答案 0 :(得分:1)

您可以使用递归来确定键,值对中的值是列表还是字典,然后相应地进行迭代。

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