使用递归函数删除嵌套字典中的空字典 [英] Remove empty dicts in nested dictionary with recursive function

查看:59
本文介绍了使用递归函数删除嵌套字典中的空字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从嵌套字典中删除非值.我的第一次努力工作正常,但不幸的是,指向现在空字典的键仍然存在.

I'm trying to remove non-values from a nested dictionary. My first effort works fine, but unfortunately keys pointing to now empty dicts still persist.

所以如果我这样做:

pass1 = stripper(my_dict)
return stripper(pass1)

这可行,但我认为可能有更优雅的嵌套解决方案?

This works, but i'm thinking a more elegant nested solution might be possible?

def stripper(self, data):
    if isinstance(data, dict):
        d = ({k: stripper(v) for k, v in data.items()
             if v not in [u'', None]})
        if d:
            return d
    else:
        return data

失败的例子,dict 下面返回为 {'foo': 'bar', 'bar': None}:

Failing example, dict below returns as {'foo': 'bar', 'bar': None}:

{
    'foo': 'bar',
    'bar': {
        'foo': None,
        'one': None
    }
}

推荐答案

dict comprehension 固然简洁,但如果你把它展开,解决方案就会变得更加明显:

The dict comprehension is certainly concise but if you expand it out, the solution becomes more obvious:

def stripper(self, data):
    new_data = {}
    for k, v in data.items():
        if isinstance(v, dict):
            v = stripper(v)
        if not v in (u'', None, {}):
            new_data[k] = v
    return new_data

这篇关于使用递归函数删除嵌套字典中的空字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆