使用python删除嵌套字典中的键及其值

1 python recursion dictionary nested

寻找一个通用的解决方案,我可以从字典中删除特定的键及其值。例如,如果dict包含以下嵌套的键值对:

data={

  "set": {
  "type": "object", #<-- should remove this key:value pair
  "properties": {
    "action": {
      "type": "string",  #<-- should NOT remove this key:value pair
      "description": "My settings"
    },
    "settings": {
      "type": "object", #<-- should remove this key:value pair
      "description": "for settings",
      "properties": {
        "temperature": {
          "type": "object", #<-- should remove this key:value pair
          "description": "temperature in degree C",
          "properties": {
            "heater": {
              "type": "object", #<-- should remove this key:value pair
              "properties": {
                "setpoint": {
                  "type": "number"
                },
              },
              "additionalProperties": false
            },

          },
          "additionalProperties": false
        },

      },
      "additionalProperties": false
    }
  },
  "additionalProperties": false
}
}
Run Code Online (Sandbox Code Playgroud)

我想要一个没有出现这个键:值对的输出字典"type":"object"。预期的输出应该产生没有"type":"object"

Aus*_*tin 5

你可以写一个递归函数:

def remove_a_key(d, remove_key):
    if isinstance(d, dict):
        for key in list(d.keys()):
            if key == remove_key:
                del d[key]
            else:
                remove_a_key(d[key], remove_key)
Run Code Online (Sandbox Code Playgroud)

并将其称为:

remove_a_key(data, 'type')
Run Code Online (Sandbox Code Playgroud)

这会递归地'type'从每个嵌套字典中删除键和它的值,无论它有多深。