Get the number of values ​​associated with a key in python dict

the dict list is similar.

[{'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 to calculate how many dict has successhow True.

I tried,

len(filter(lambda x: x, [i['success'] for i in s]))

How can I make it more elegant using pythonic?

+4
source share
3 answers

You can use sum()to add your booleans; Trueequal to 1 in a numerical context, Falseequal to 0:

sum(d['success'] for d in s)

This works because the Python type boolis a subclass intfor historical reasons.

If you want to make this explicit, you can use a conditional expression, but from my point of view, readability will not improve:

sum(1 if d['success'] else 0 for d in s)
+9

-

len(filter(lambda x:x['success'], s))

, "" dict

len(filter(lambda x:x.get('success',False), s))

+1

:

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

:

1

Pythonic, .

+1

Source: https://habr.com/ru/post/1627783/


All Articles