删除具有空值的键

时间:2014-01-08 10:19:56

标签: python dictionary

如何删除没有任何值的dict中的键。我有一个词典:

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

我想删除值为空的键。我需要输出:

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

怎么做?

3 个答案:

答案 0 :(得分:4)

使用字典理解:

>>> {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 v


如果要修改原始字典本身(这将影响对dict对象的所有引用):

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

如果你真的需要在一行中这样做:

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

这太丑了。它列出了d中具有“空白”值的所有键,然后遍历此列表,从d中删除键(以避免在迭代期间从字典中删除不安全的项)

我建议三行更具可读性:

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

如果可以接受新的dict,请使用dict comprehension

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