Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

best way of counting number of items based on condition python

Hi guys I have multiple conditions to check on a array of objects for example :

My sample array is like this

[{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"}]

as these records will be in 10000’s I want to calculate total sum of these in best way possible .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently doing like this

   view_count = [element for element in user_record if element['type'] == "viw"  ]
   edit_count = [element for element in user_record if element['type'] == "edit"]
   crt_count = [element for element in user_record if element['type'] =="crt"]

   and then len(crt_count) ,len(edit_count) ,len(view_count) 

which seems to me a little expensive . kindly guide can I do it in optimize way ?

and 2nd question can I use OR condition with if in this list comprehension ?

>Solution :

Just collect each of the ‘types’ into a dictionary key and count them with it’s value

result = {}
for element in user_record:
   try:
        result[element["type"]] += 1
   except KeyError: 
        result[element["type"]] = 1

per comment from @Not A Robot :
"another way for essentially the same idea:"

collections.Counter(map(operator.itemgetter('type'), my_list))

Second Question: Answer is yes you can use or like this:

edit_count = [element for element in user_record if element['type'] == "edit" or element['type'] == 'viw']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading