Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List of dictionaries. Count elements based on key of dictionary [closed]

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)
like image 661
Abhinav Goel Avatar asked Dec 06 '22 15:12

Abhinav Goel


2 Answers

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
like image 71
falsetru Avatar answered Feb 23 '23 12:02

falsetru


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
like image 37
Iron Fist Avatar answered Feb 23 '23 12:02

Iron Fist