Removing entries from a dictionary based on values

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}

Leave a Comment