Removing entries from a dictionary based on values
Solution 1:
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}
Solution 2:
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.