MHS
MHS

Reputation: 2350

How to remove empty entries from a list in a dictionary using python

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']}

Upvotes: 1

Views: 1342

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121148

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']}

Upvotes: 3

Neil
Neil

Reputation: 489

you can use ifilter in itertools

from itertools import ifilter

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

Upvotes: 0

Related Questions