python中字典回调循环处理字典中值为None或特定值替换为其它值的方法。
#清除值为空的键值对,但保留值为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 isinst
共有 0 条评论