Remove key and its value in nested dictionary using python

£可爱£侵袭症+ 提交于 2020-06-13 09:22:40

问题


Looking for a generic solution where I can remove the specific key and its value from dict. For example, if dict contains the following nested key-value pair:

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

I want an output dict without "type":"object" across the occurrence of this key:value pair. The expected output should produce the result without "type":"object"


回答1:


You can write a recursive function:

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)

and call it as:

remove_a_key(data, 'type')

This recursively removes 'type' key and it's value from each nested dictionary no matter how deep it is.




回答2:


Use python module nested-lookup to play with any kind of nested documents. Checkout https://pypi.org/project/nested-lookup/ for more info.

In your case you need to use method nested_delete to delete all occurrences of a key.

Usage:

from nested_lookup import nested_delete

print(nested_delete(data, 'type'))


来源:https://stackoverflow.com/questions/58938576/remove-key-and-its-value-in-nested-dictionary-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!