Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing entries from a dictionary based on values

Tags:

python

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?

like image 671
OneMoreError Avatar asked Mar 01 '13 13:03

OneMoreError


People also ask

Does dictionary have remove function?

Dictionary remove() Method in JavaThe remove() method of Dictionary Class accepts a key as a parameter and removes the corresponding value mapped to the key. Parameters: The function accepts a parameter key which denotes the key which is to be removed from the dictionary along with its mappings.

Which are the ways to delete element from dictionary explain with example?

Removing elements from Dictionary We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value . The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary.


2 Answers

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} 
like image 94
Niklas B. Avatar answered Oct 05 '22 17:10

Niklas B.


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.

like image 33
Volatility Avatar answered Oct 05 '22 16:10

Volatility