1

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

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.