如果所有值都为空字符串,则从列表中删除dictionaire

时间:2013-12-09 17:55:11

标签: python

我有一个dictionaires列表(列表中的所有词典都有相同的9个键),我想删除列表中7个键的值为''的词典。但是,如果至少有一个键具有值,那么它将保留整个词典(包括其他键所在的位置)

例如(只有3个键可以简化)

[{Key1:JJ, Key2:GG, Key3:''},{Key1:'', Key2:'', Key3:''},{Key1:'', Key2:GG, Key3:''},{Key1:'', Key2:'', Key3:''}]

输出为

[{Key1:JJ, Key2:GG, Key3:''},{Key1:'', Key2:GG, Key3:''}]

欢迎任何帮助!

2 个答案:

答案 0 :(得分:5)

使用列表推导和any()

[d for d in inputlist if any(d.itervalues())]

在Python 3中使用any(d.values())

如果输入列表中存在任何非空值,则

any()仅返回True。通过使用d.itervalues(),我们测试字典中的最小值,以证明它们之间存在非空值。

演示:

>>> inputlist = [{'Key1': 'JJ', 'Key2': 'GG', 'Key3':''}, {'Key1': '', 'Key2': '', 'Key3': ''}, {'Key1': '', 'Key2': 'GG', 'Key3': ''}, {'Key1': '', 'Key2': '', 'Key3': ''}]
>>> [d for d in inputlist if any(d.itervalues())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]

如果除了空字符串之外的任何其他值也可以被测试为假(例如None0),那么您也可以使用显式测试:

[d for d in inputlist if any(v != '' for v in d.itervalues())]

答案 1 :(得分:2)

使用list comprehension根据dict.values *返回的内容过滤密钥:

>>> dct = [{'Key1':'JJ', 'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''},{'Key1':'',
'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''}]
>>> [x for x in dct if any(y != '' for y in x.values())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]
>>>

或者,如果值都是字符串,那么您可以这样做:

>>> dct = [{'Key1':'JJ', 'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''},{'Key1':'',
'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''}]
>>> [x for x in dct if any(x.values())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]
>>>

这是有效的,因为空字符串在Python中评估为False


*注意:如果您使用的是Python 2.x,则应使用dict.itervalues代替dict.values。它更有效,因为它返回迭代器而不是列表。