【问题标题】:Generic Function to replace value of a key in a dict or nested dict or list of dicts用于替换字典或嵌套字典或字典列表中键值的通用函数
【发布时间】:2018-03-28 03:48:24
【问题描述】:

所以我有一个这样的字典:

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

也可以是这样的

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

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

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

但最后我想要相同的字典对象 - 我传递的 dict_obj 但具有新值,它应该适用于上述任何类型的字典 摸不着头脑怎么解决:(

【问题讨论】:

  • 从找到钥匙开始...
  • 如果你return dict,你通常不需要——甚至不希望——它与你传入的一样。另一方面,如果你就地修改 dict ,您通常不需要或不想退回它。 (这就是为什么像 list.sortdict.update 这样的内置方法以及 stdlib 中类似的变异函数几乎总是返回 None。)

标签: python python-2.7 dictionary


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2016-04-14
    • 2023-01-23
    • 2021-05-10
    • 2021-08-09
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多