1

I have a dictionary like this:

data = {'Fruits' : ['Mango', 'Banana', '', '', 'Apple'],
        'Trees' : ['Pine', 'Bamboo', '', '', '', '', ''],
        'Laptops' : ['Sony', '', '', 'LG', 'Acer', '']}

How can I remove all the EMPTY items from every list in dictionary, so it may look like this:

data = {'Fruits' : ['Mango', 'Banana', 'Apple'],
        'Trees' : ['Pine', 'Bamboo'],
        'Laptops' : ['Sony', 'LG', 'Acer']}

2 Answers 2

3

With a dict comprehension and filter():

data = {k: filter(bool, v) for k, v in data.iteritems()}

or, for python 2.6 and older, where you do not yet have dict comprehensions:

data = dict((k, filter(bool, v)) for k, v in data.iteritems())

or a list comprehension for the value if you are on Python 3:

data = {k: [i for i in v if i] for k, v in data.iteritems()}

Quick demo:

>>> data = {'Fruits' : ['Mango', 'Banana', '', '', 'Apple'],
...         'Trees' : ['Pine', 'Bamboo', '', '', '', '', ''],
...         'Laptops' : ['Sony', '', '', 'LG', 'Acer', '']}
>>> {k: filter(bool, v) for k, v in data.iteritems()}
{'Laptops': ['Sony', 'LG', 'Acer'], 'Trees': ['Pine', 'Bamboo'], 'Fruits': ['Mango', 'Banana', 'Apple']}
Sign up to request clarification or add additional context in comments.

8 Comments

You mean "a list comprehension if you are on Python 2", right?
Why filter(bool, v)? Isn't filter(None, v) exactly the same?
@BernhardKausler no, filter returns a list in Python 2, but an iterator in Python 3, hence the list comprehension.
@wRAR Python 2 has no dict comprehensions, only list comprehensions.
ah, they added dict comprehensions starting from Python 2.7
|
0

you can use ifilter in itertools

from itertools import ifilter

for key,val in data.iteritems():
    data[key] = list(ifilter(lambda x: x!='', val))

1 Comment

Using ifilter() then calling list() on it completely defeats the purpose. You may as well use filter() directly then, which will be faster. ifilter takes bool as a filter too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.