You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除嵌套字典中的所有零值,生成目标字典?

移除嵌套字典中的所有零值

如果只是处理两层嵌套的字典,用嵌套字典推导式就能快速完成:

original_dict = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}
cleaned_dict = {k: {sub_k: sub_v for sub_k, sub_v in v.items() if sub_v != 0} for k, v in original_dict.items()}

执行后cleaned_dict的结果为:

{'a': {'m': 1}, 'b': {'x': 1}}

如果需要支持任意深度的嵌套字典,可以写一个递归函数,同时还能自动过滤处理后为空的子字典:

def remove_zero_values(d):
    cleaned = {}
    for k, v in d.items():
        if isinstance(v, dict):
            cleaned_sub_dict = remove_zero_values(v)
            if cleaned_sub_dict:
                cleaned[k] = cleaned_sub_dict
        elif v != 0:
            cleaned[k] = v
    return cleaned

original_dict = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}
cleaned_dict = remove_zero_values(original_dict)

内容的提问来源于stack exchange,提问作者LegendWK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:21:34