Python 如何删除嵌套字典,其中所有元素均为无
例如,我有一个嵌套的Python 如何删除嵌套字典,其中所有元素均为无,python,python-3.x,dictionary,nested,Python,Python 3.x,Dictionary,Nested,例如,我有一个嵌套的dict: nest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"tech":"geekbuzz", "OS":None}, "dict_3": {"fruit":None, "PRICE":None}} 我需要得到: new_dest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"
dict
:
nest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"tech":"geekbuzz", "OS":None}, "dict_3": {"fruit":None, "PRICE":None}}
我需要得到:
new_dest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"tech":"geekbuzz", "OS":None}}
您可以在此处使用内置的:
它保留具有任何非None
值的子词典
您也可以在此处使用内置功能:
>>> {k: v1 for k, v1 in nest_dic.items() if not all(v2 is None for v2 in v1.values())}
{'dict_1': {'hello': 'world', 'python': 'programming'}, 'dict_2': {'tech': 'geekbuzz', 'OS': None}}
它保留了哪些子字典中的值都不是None
另作为None
比较的旁注,请参见以下中的编程建议:
应始终使用is
或is not
进行与None等单例的比较,切勿使用相等运算符
另外,当您真正的意思是如果x不是None时,请注意编写if x
——例如,当测试默认为None的变量或参数是否设置为其他值时。另一个值的类型(如容器)在布尔上下文中可能为false
>>> {k: v1 for k, v1 in nest_dic.items() if not all(v2 is None for v2 in v1.values())}
{'dict_1': {'hello': 'world', 'python': 'programming'}, 'dict_2': {'tech': 'geekbuzz', 'OS': None}}