list of dict is like .
[{'id': 19, 'success': True, 'title': u'apple'},
{'id': 19, 'success': False, 'title': u'some other '},
{'id': 19, 'success': False, 'title': u'dont know'}]
I want count of how many dict have success
as True
.
I have tried,
len(filter(lambda x: x, [i['success'] for i in s]))
How can I make it more elegant using pythonic way ?
You could use sum()
to add up your boolean values; True
is 1 in a numeric context, False
is 0:
sum(d['success'] for d in s)
This works because the Python bool
type is a subclass of int
, for historic reasons.
If you wanted to make it explicit, you could use a conditional expression, but readability is not improved with that in my opinion:
sum(1 if d['success'] else 0 for d in s)
Another way is
len(filter(lambda x:x['success'], s))
it can crash if you don't have 'success' in dict
len(filter(lambda x:x.get('success',False), s))
may do the job
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With