sam
sam

Reputation: 19214

remove the keys which has blank values

how to remove keys in a dict which do not have any value. I have a dict as :

d = {'CB': '', 'CA': [-7.5269999504089355, -2.2330000400543213, 6.748000144958496], 'C': [-8.081000328063965, -3.619999885559082, 6.406000137329102], 'N': [-6.626999855041504, -2.318000078201294, 7.9029998779296875], 'H':''}

I want to remove keys which values are blank. I need output as :

d = {'CA': [-7.5269999504089355, -2.2330000400543213, 6.748000144958496], 'C': [-8.081000328063965, -3.619999885559082, 6.406000137329102], 'N': [-6.626999855041504, -2.318000078201294, 7.9029998779296875]}

how to do this?

Upvotes: 1

Views: 113

Answers (3)

johnsyweb
johnsyweb

Reputation: 141998

If you really need to do this in one-line:

for k in [k for k,v in d.iteritems() if not v]: del d[k]

This is ugly. It makes a list of all of the keys in d that have a "blank" value and then iterates over this list removing the keys from d (to avoid the unsafe removal of items from dictionary during iteration).

I'd suggest that three lines would be more readable:

blanks = [k for k,v in d.iteritems() if not v]
for k in blanks:
    del d[k]

If making a fresh dict is acceptable, use a dict comprehension:

d2 = {k:v for k,v in d.iteritems() if not v}

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

Use a dict-comprehension:

>>> {k:v for k, v in d.items() if v != ''}
{'N': [-6.626999855041504, -2.318000078201294, 7.9029998779296875], 'CA': [-7.5269999504089355, -2.2330000400543213, 6.748000144958496], 'C': [-8.081000328063965, -3.619999885559082, 6.406000137329102]}

If by empty you meant any falsy value then use just if v.


If you want to modify the original dict itself(this will affect all the references to the dict object):

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

Upvotes: 4

praveen
praveen

Reputation: 3263

>> {key:value for key, value in d.items() if value}

Upvotes: 2

Related Questions