+3 votes
in Programming Languages by (56.5k points)
I want to delete all keys from a dictionary whose value is 0. Is there any Pythonic way or function for it?


aa= {'a': 0, 'b':1, 'c':0, 'd':2}


aa= {'b':1, 'd':2}

1 Answer

+2 votes
by (73.8k points)
selected by
Best answer

You can use dictionary comprehension to remove all keys from the dictionary whose value is 0. You need to go thru each (key, value) pair and discard keys with value =0.

Here is an example:

>>> aa= {'a': 0, 'b':1, 'c':0, 'd':2}
>>> aa
{'a': 0, 'b': 1, 'c': 0, 'd': 2}
>>> aa={k:v for k, v in aa.items() if v!=0}
>>> aa
{'b': 1, 'd': 2}