根据键值过滤python中的嵌套字典

sau*_*abh 1 python dictionary

如何根据键值过滤python中的嵌套字典:

d = {'data': {'country': 'US', 'city': 'New York', 'state': None},
     'tags': ['US', 'New York'],
     'type': 'country_info',
     'growth_rate': None
     }
Run Code Online (Sandbox Code Playgroud)

我想过滤这个字典以消除NoneType值,因此产生的字典应该是:

d = {'data': {'country': 'US', 'city': 'New York'},
     'tags': ['US', 'New York'],
     'type': 'country_info',
     }
Run Code Online (Sandbox Code Playgroud)

此外,dict可以有多个嵌套级别.我想从dict中删除所有NoneType值.

Gar*_*tty 7

你可以用dict理解很容易地递归地定义它.

def remove_keys_with_none_values(item):
    if not hasattr(item, 'items'):
        return item
    else:
        return {key: remove_keys_with_none_values(value) for key, value in item.items() if value is not None}
Run Code Online (Sandbox Code Playgroud)

递归在Python中没有太优化,但考虑到可能的嵌套数量相对较少,我不担心.

在我们跳跃之前看起来并不太Pythonic,我认为这是一个比捕获异常更好的选择 - 因为它可能不是dict大部分时间的值(我们可能有更多的叶子而不是分支).

还要注意,在Python 2.x中,你可能想换入iteritems()items().