How to remove all 0 from a dictionary in python?

dictionary, python

Solution

Use a dict-comprehension:

In [94]: dic={'1': 2, '0': 0, '3': 4, '2': 4, '5': 1, '4': 1, '7': 0, '6': 0, '9': 0, '8': 0}

In [95]: {x:y for x,y in dic.items() if y!=0}
Out[95]: {'1': 2, '2': 4, '3': 4, '4': 1, '5': 1}

Problem

Lets say I have a dictionary like this: ``` {'1': 2, '0': 0, '3': 4, '2': 4, '5': 1, '4': 1, '7': 0, '6': 0, '9': 0, '8': 0} ``` I want to remove all items with a value of zero So that it comes out like this ``` {'1': 2, '3': 4, '2': 4, '5': 1, '4': 1} ```

Original source

Related problems