6

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}
Jett
  • 2,421
  • 5
  • 16
  • 14
  • Write some code. Why I downvoted this question: http://meta.stackexchange.com/a/149138/133242 And why are you using a dict instead of a list? – Matt Ball Apr 04 '13 at 22:00
  • 1
    Close cousin, if not exact duplicate: [Remove all occurences of a value from a Python list](http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list) – Robert Harvey Apr 04 '13 at 22:00
  • @MattBall I'm learning dictionaries not lists – Jett Apr 04 '13 at 22:03
  • 3
    Well I been trying to do this for like an hour now. So I decided to seek help. Sorry I asked a question – Jett Apr 04 '13 at 22:10

2 Answers2

14

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}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
6

Use a dictionary comprehension:

{k: v for k, v in d.items() if v}
Blender
  • 289,723
  • 53
  • 439
  • 496