Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get count of values associated with key in dict python

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 ?

like image 732
Nishant Nawarkhede Avatar asked Dec 18 '22 19:12

Nishant Nawarkhede


2 Answers

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)
like image 150
Martijn Pieters Avatar answered Jan 11 '23 11:01

Martijn Pieters


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

like image 26
ikhtiyor Avatar answered Jan 11 '23 10:01

ikhtiyor