drop a key from dictionary by value

Question:

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

dict_ = {"a": "A", "b": "B", "c": None, "d": " "}
Asked By: elephant_man

||

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'}
Answered By: Mehrdad Pedramfar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.