Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter values of dictionary [duplicate]

I wanna filter values of dictionary.

d1 = {'a': 0, 'b': 0, 'c': 8, 'd': 7}

What is the pythonic way to do that.

d={}

for k,v in d1.items():
   if v>0:
      d[k]=v

I couldn't use filter to get the same reuslts.

filter(..)

Is there any elegant pythonic way to do that ?

like image 686
user3378649 Avatar asked Dec 18 '14 01:12

user3378649


1 Answers

You can use dictionary comprehension, to create a dictionary with the filtered values, like this

>>> {key: d1[key] for key in d1 if d1[key] > 0}
{'c': 8, 'd': 7}

You can also use dict.items() like this

>>> {key: value for key, value in d1.items() if value > 0}
{'c': 8, 'd': 7}

Note: Using dict.iteritems() will be more memory efficient in Python 2.7, as dict.items() will create a list of tuples with all the key-value pairs.

If your intention is to just remove the values which are 0, then you can even shorten it like this

>>> {key: value for key, value in d1.items() if value}
{'c': 8, 'd': 7}
like image 147
thefourtheye Avatar answered Sep 18 '22 02:09

thefourtheye