fledgling February 2016

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 ?

Answers


Martijn Pieters February 2016

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)


ikhtiyor February 2016

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


Pouria Hadjibagheri February 2016

Here is how you do it elegantly:

args = [
    {'id': 19, 'success': True, 'title': u'apple'},
    {'id': 19, 'success': False, 'title': u'some other '},
    {'id': 19, 'success': False, 'title': u'dont know'}
]


count_success = lambda x: 1 if x['success'] else 0

success_list = map(count_success, args)

print(sum(success_list))  # Python 3
print sum(success_list)   # Python 2

Displays:

1

This is as Pythonic as it gets.

Post Status

Asked in February 2016
Viewed 2,664 times
Voted 6
Answered 3 times

Search




Leave an answer