drop a key from dictionary by value

Viewed 25

How drop items with None or empty values from a given dictionary?

dict_ = {"a": "A", "b": "B", "c": None, "d": " "}
1 Answers

Try this in one line using dictionary comprehension:

dict_ = {"a": "A", "b": "B", "c": None, "d": " "}
dict_ = {k:v for k,v in dict_.items() if v and v != ' '}

and the result will be:

Out[4]: {'a': 'A', 'b': 'B'}
Related