#清除值为空的键值对,但保留值为0的
def clean_empty(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (clean_empty(v) for v in d) if (v or v == 0)]
return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if (v or v == 0)}
#将NoneType替换为其它字符(保留了key),如'v'
def replace_empty(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v if (v or v == 0) else 'v' for v in (replace_empty(v) for v in d)]
return {k: (v if (v or v == 0) else 'v') for k, v in ((k, replace_empty(v)) for k, v in d.items())}
a = None
b = {0:{5:54}, 1:545,2:{11:a, 5:5},3:{565:{'ss':a,'sss':{4:{5:a}}}},4:a}
#print(clean_empty(b))
print(replace_empty(b))
结果: