46

I have a dictionary with character-integer key-value pair. I want to remove all those key value pairs where the value is 0.

For example:

>>> hand
{'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}

I want to reduce the same dictionary to this:

>>> hand
{'m': 1, 'l': 1}

Is there an easy way to do that?

approxiblue
  • 6,982
  • 16
  • 51
  • 59
OneMoreError
  • 7,518
  • 20
  • 73
  • 112

4 Answers4

37

You can use a dict comprehension:

>>> { k:v for k, v in hand.items() if v }
{'m': 1, 'l': 1}

Or, in pre-2.7 Python, the dict constructor in combination with a generator expression:

>>> dict((k, v) for k, v in hand.iteritems() if v)
{'m': 1, 'l': 1}
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
  • 2
    Note that this removes all values that evaluate to `False`. This is subtly different if you have non-integer values as well. – Gareth Latty Mar 01 '13 at 13:24
  • @Lattyware: It looks to me like OP only has integers as values... I can only work with what I get :) – Niklas B. Mar 01 '13 at 13:37
  • using `.items` instead of `.iteritems` can be very inefficient for larger data sets. – Don Aug 28 '14 at 14:24
  • @Don that depends on the version of Python you use. I'm usually assuming the newest version unless otherwise specified. Agreed though for my second example – Niklas B. Aug 28 '14 at 15:35
  • @NiklasB. Thanks for the info, I spend so much time in 2.7 I actually didn't know about that change. Good stuff – Don Sep 02 '14 at 13:24
13

If you don't want to create a new dictionary, you can use this:

>>> hand = {'a': 0, 'i': 0, 'm': 1, 'l': 1, 'q': 0, 'u': 0}
>>> for key in list(hand.keys()):  ## creates a list of all keys
...     if hand[key] == 0:
...             del hand[key]
... 
>>> hand
{'m': 1, 'l': 1}
>>> 
R7L208
  • 85
  • 14
Fabian
  • 4,160
  • 20
  • 32
11
hand = {k: v for k, v in hand.iteritems() if v != 0}

For Pre-Python 2.7:

hand = dict((k, v) for k, v in hand.iteritems() if v != 0)

In both cases you're filtering out the keys whose values are 0, and assigning hand to the new dictionary.

Volatility
  • 31,232
  • 10
  • 80
  • 89
4

A dict comprehension?

{k: v for k, v in hand.items() if v != 0}

In python 2.6 and earlier:

dict((k, v) for k, v in hand.items() if v != 0)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124