user2950162
user2950162

Reputation: 1011

remove dictionaire from list if ALL values are empty string

I have a list of dictionaires (all dictionaires in the list have the same 9 keys) and I would like to delete the dictionaires on the list where the value of the 9 keys is ' '. But if at least one key have a value it would keep the whole dictionaire (including the other keys where it is ' ' )

For example (with only 3 keys to simplify)

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

The output would be

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

Any help welcome!

Upvotes: 0

Views: 58

Answers (2)

user2555451
user2555451

Reputation:

Use a list comprehension to filter the keys based on what is returned by 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': ''}]
>>>

Or, if the values are all strings, then you can just do this:

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

This works because empty strings evaluate to False in Python.


*Note: If you are on Python 2.x, you should use dict.itervalues in place of dict.values. It is more efficient because it returns an iterator instead of a list.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124548

Use a list comprehension and any():

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

Use any(d.values()) in Python 3.

any() only returns True if there are any non-empty values in the input list. By using d.itervalues() we test the minimal number of values in the dictionary to prove there is a non-empty value among them.

Demo:

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

If any values other than the empty strings could be tested as false as well (such as None or 0), you can use an explicit test as well:

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

Upvotes: 5

Related Questions