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

E.g.

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

output

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

1 Answer

+2 votes
by (51.1k 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}
>>>


...