Reputation: 1011
I am trying to filter a list of dictionaries based on the number of keys with empty values (for empty value I would like to consider empty strings '' and empty lists []).
for example
list_products=[{'index':1, 'type':'house', 'price': '', 'bar': []},{'index':1, 'type':'house', 'price': 'expensive', 'bar': ['yes','big']}]
I need to eliminate the first dictionary of the list (number of keys with value is 2 or less). The actual dictionary has many more keys and I would prefer a solution where I do not need to specify the key in an if statement to check for its value...
is it possible to have something like that...
list_products=[d for d in list_products if len(d.values())<2]
It does not work beacuse an empty list is not seen as empty by python... any suggestions?
Thanks in advance
Upvotes: 0
Views: 291
Reputation: 25954
You want something like
[d for d in list_products if sum(bool(v) for v in d.values()) > 2]
explanation: you can sum
boolean values: True
coerces to one.
Upvotes: 5
Reputation: 9311
result = []
treshold = 2
for item in list_products:
non_empty = 0
for key in item:
if item[key] not in ('', []):
non_empty += 1
if non_empty > treshold:
result.append(item)
Here you just set your treshold and get what you want in result
list.
Upvotes: 0