使用python删除嵌套字典中的键及其值 [英] Remove key and its value in nested dictionary using python
本文介绍了使用python删除嵌套字典中的键及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
寻找一种通用解决方案,在该解决方案中,我可以从dict中删除特定键及其值.例如,如果 dict 包含以下嵌套的键值对:
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
}
}
我希望在整个key:value对出现时没有"type":"object"
的输出 dict .预期的输出应生成没有"type":"object"
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"
推荐答案
您可以编写一个递归函数:
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)
并将其称为:
remove_a_key(data, 'type')
这将递归地删除'type'
键,并且无论它有多深,它都会从每个嵌套字典中删除.
This recursively removes 'type'
key and it's value from each nested dictionary no matter how deep it is.
这篇关于使用python删除嵌套字典中的键及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文