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}
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}
Use a dictionary comprehension:
{k: v for k, v in d.items() if v}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With