I read a csv file, using DictReader
.
I have a list of dictionaries:
eg:
a = [{'Name':'A','Class':'1'},{'Name':'B','Class':'1'},{'Name':'C','Class':'2'}]
I want to count the number of entries in the list that have 'Class' == 1.
Is it possible to do it without a loop?
EDIT:
I have tried the following:
count = 0
for k in a:
if k['Class'] == '1':
count += 1
print(count)
Using sum
with generator expression:
>>> xs = [{'Name':'A','Class':'1'},
{'Name':'B','Class':'1'},
{'Name':'C','Class':'2'}]
>>> sum(x.get('Class') == '1' for x in xs)
2
Using list comprehension as well, to retrieve dictionaries matching your criteria then calculating its len
:
>>> len([d for d in a if d.get('Class')=='1'])
2
EDIT: Timing Profile under Python3.5.2
>>>import timeit
>>>
>>> timeit.timeit(stmt="len([d for d in a if d.get('Class')=='1'])", globals={'a':a})
0.8056499021768104
>>>
>>> timeit.timeit(stmt="sum(x.get('Class') == '1' for x in a)", globals={'a':a})
0.9977147589670494
>>>
>>> timeit.timeit(stmt="len(list(filter(lambda x: x.get('Class')=='1' , a)))", globals={'a':a})
1.3259506113099633
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