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 ?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With