Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all 0 from a dictionary in python? [closed]

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}
like image 738
Jett Avatar asked Apr 04 '13 21:04

Jett


2 Answers

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}
like image 167
Ashwini Chaudhary Avatar answered Sep 30 '22 18:09

Ashwini Chaudhary


Use a dictionary comprehension:

{k: v for k, v in d.items() if v}
like image 32
Blender Avatar answered Sep 30 '22 17:09

Blender