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 .
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']