Reputation: 3667
I have a list that looks like this:
[{'name':'bob'},{'name':''},{'name':'test2'}]
The dictionary object is not really empty in the list, so how do I remove this 'empty' object that is not really empty? the new list should look like this:
[{'name':'bob'},{'name':'test2'}]
I have tried:
[i for i in mylist if i]
but since the dictionary object is not completely empty I am not able to drop it, I think.
edit:
I put the below code in my JSON data clean up process like so:
for json in list:
try:
name = extract_json
name = [i for i in name if len(i["name"]) > 0]
except:
name = None
I want to do the list clean only if it is needed.
Upvotes: 0
Views: 149
Reputation: 16573
You can try this. It is foolproof for dicts with more than one key and also data types other than string:
mylist = [{'name':'bob'},{'name':''},{'name':'test2'}]
new_list = [d for d in mylist if any(d.values())]
Upvotes: 1
Reputation: 1745
You need to test the name
key of each dict
, I would do it by checking the length of the name is greater than zero:
>>> d = [{'name':'bob'},{'name':''},{'name':'test2'}]
>>> [i for i in d if len(i["name"]) > 0]
[{'name': 'bob'}, {'name': 'test2'}]
Upvotes: 1