marsx
marsx

Reputation: 715

removing dictionary entries with no values- Python

If I have a dictionary, and I want to remove the entries in which the value is an empty list [] how would I go about doing that?

I tried:

for x in dict2.keys():
    if dict2[x] == []:
        dict2.keys().remove(x)

but that didn't work.

Upvotes: 8

Views: 16760

Answers (8)

azgrammer
azgrammer

Reputation: 11

def dict_without_empty_values(d):
    return {k:v for k,v in d.iteritems() if v}


# Ex;
dict1 = {
    'Q': 1,
    'P': 0,
    'S': None,
    'R': 0,
    'T': '',
    'W': [],
    'V': {},
    'Y': None,
    'X': None,
}

print dict1
# {'Q': 1, 'P': 0, 'S': None, 'R': 0, 'T': '', 'W': [], 'V': {}, 'Y': None, 'X': None}

print dict_without_empty_values(dict1)
# {'Q': 1}

Upvotes: 1

KrzysztofCiba
KrzysztofCiba

Reputation: 31

Why not just keep those which are not empty and let the gc to delete leftovers? I mean:

dict2 = dict( [ (k,v) for (k,v) in dict2.items() if v] )

Upvotes: 3

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

With generator object instead of list:

a = {'1': [], 'f':[1,2,3]}
dict((data for data in a.iteritems() if data[1]))

Upvotes: 1

JBernardo
JBernardo

Reputation: 33387

Newer versions of python support dict comprehensions:

dic = {i:j for i,j in dic.items() if j != []}

These are much more readable than filter or for loops

Upvotes: 14

Jeremy Banks
Jeremy Banks

Reputation: 129715

.keys() provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. You need to use del dictionary[key] or dictionary.pop(key) to remove it.

Because of the behaviour in some version of Python, you need to create a of copy of the list of your keys for things to work right. So your code would work if written as:

for x in list(dict2.keys()):
    if dict2[x] == []:
        del dict2[x]

Upvotes: 12

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29707

Clean one, but it will create copy of that dict:

dict(filter(lambda x: x[1] != [], d.iteritems()))

Upvotes: 1

Ravi
Ravi

Reputation: 3756

for x in dict2.keys():
    if dict2[x] == []:
        del dict2[x]

Upvotes: 3

MattH
MattH

Reputation: 38247

for key in [ k for (k,v) in dict2.items() if not v ]:
  del dict2[key]

Upvotes: 1

Related Questions