MAAS
MAAS

Reputation: 11

how to remove nested dictionaries where all elements inside are None

For example i have this nested dict:

nest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"tech":"geekbuzz", "OS":None}, "dict_3": {"fruit":None, "PRICE":None}}

I need to get:

new_dest_dic = {"dict_1":{"hello":"world", "python":"programming"}, "dict_2": {"tech":"geekbuzz", "OS":None}}

Upvotes: 1

Views: 45

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

You can use any() built-in here with a Python Dictionary Comprehension:

>>> {k: v1 for k, v1 in nest_dic.items() if any(v2 is not None for v2 in v1.values())}
{'dict_1': {'hello': 'world', 'python': 'programming'}, 'dict_2': {'tech': 'geekbuzz', 'OS': None}}

Which keeps sub dictionaries that have any value that is not None.

You could also use the all() built-in function here as well:

>>> {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}}

Which keeps Which keeps sub dictionaries that all don't have values that are None.

Also as a side note for None comparisons, from Programming Recommendations in PEP 8:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

Upvotes: 1

Related Questions