Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (17.6k points)

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)

1 Answer

0 votes
by (41.4k points)

Yes,it is possible to do it without a loop by 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

Gain practical exposure with data science projects in Intellipaat's Data Science course online.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...