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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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}
Method 2
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}
>>>
Method 3
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.
Method 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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0