从具有嵌套结构的字典中删除混合数据类型的null和空对象



在我问的一个类似问题的后面,如何清理包含各种数据类型的字典:null、空列表、空dict等,嵌套级别不同,例如

{
"key":"value",
"key1": {},
"key2": [],
"key3": True,
"key4": False,
"key5": None,
"key6": [1,2,3],
"key7": {
"subkey": "subvalue"
},
"key8": {
"subdict": {
"subdictkey": "subdictvalue", 
"subdictkey1": {},
"subdictkey2": [],
"subdictkey3": None
}
}
}

成为:

{
"key":"value",
"key3": True,
"key4": False,
"key6": [1,2,3],
"key7": {
"subkey": "subvalue"
},
"key8": {
"subdict": {
"subdictkey": "subdictvalue"
}
}
}

该解决方案应该适用于n个级别的嵌套(而不仅仅是1个级别(。显然,我想避免嵌套循环(特别是当n可以等于3或4时(,唯一的解决方案是使结构变平吗?有没有更优雅的方式?

编辑:基于@Ch3steR的回答,并考虑到我遇到的包含null的列表问题,这是最后的工作函数:

def recur(n_dict,new_d={}):
global counter
for key,val in n_dict.items():
if val or isinstance(val,bool) or (isinstance(val,list) and any(elem is not None for elem in val)):
if (isinstance(val,list) and any(elem is None for elem in val)):
counter=counter+1
else:
new_d={**new_d,**{key:val}}
if isinstance(val,dict):
new_d[key]=recur(val)
return new_d

在处理任意嵌套的字典时,可以使用递归

试试这个。

def recur(n_dict,new_d={}):
for key,val in n_dict.items():
if val or isinstance(val,bool):
new_d={**new_d,**{key:val}}
if isinstance(val,dict):
new_d[key]=recur(val)
return new_d

a={
"key":"value",
"key1": {},
"key2": [],
"key3": True,
"key4": False,
"key5": None,
"key6": [1,2,3],
"key7": {
"subkey": "subvalue"
},
"key8": {
"subdict": {
"subdictkey": "subdictvalue", 
"subdictkey1": {},
"subdictkey2": [],
"subdictkey3": None
}
}
}
print(recur(a))
{'key': 'value',
'key3': True,
'key4': False,
'key6': [1, 2, 3],
'key7': {'subkey': 'subvalue'},
'key8': {'subdict': {'subdictkey': 'subdictvalue'}}}

recur(n_dict,new_d={})使用可变的默认参数。

注:

切勿在适当位置突变new_d,否则您将遇到此问题

检查默认参数是否已更改的方法之一是使用__defaults__

>>>recur(a)
>>>recur.__defaults__
({},) 
>>>recur(a)
>>>recur.__defaults__
({},) 

最新更新