Skip to main content
 首页 » 编程设计

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

2025年05月04日15Leo_wl

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

d = {'data': {'country': 'US', 'city': 'New York', 'state': None}, 
     'tags': ['US', 'New York'], 
     'type': 'country_info', 
     'growth_rate': None 
     } 

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

d = {'data': {'country': 'US', 'city': 'New York'}, 
     'tags': ['US', 'New York'], 
     'type': 'country_info', 
     } 

此外,字典可以有多层嵌套。我想从字典中删除所有 NoneType 值。

请您参考如下方法:

您可以使用 dict comprehension 很容易地递归定义它.

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} 

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

Look before we leap 并不太像 Pythonic,我认为这是比捕获异常更好的选择 - 因为大多数时候该值可能不是 dict(它是很可能我们的叶子比 Twig 多。

另请注意,在 Python 2.x 中,您可能希望将 iteritems() 换成 items()。