pythonjson

How to compare with other json objects's value


I have a list :

a_list :

[{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'}, 
{'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'}, 
{'score': 65, 'credit': 5, 'class': 'B01', 'subject': 'science'}, 
{'score': 35, 'credit': 5, 'class': 'C02', 'subject': 'math'}]

And I query (django) from db get a list, each subject has its own pass_mark

pass_list =  ClassData.objects.values('subject','pass_mark')

pass_list:

[{'pass_mark': 50, 'subject_all': u'math'}, 
{'pass_mark':70, 'subject_all': u'science'}, 
{'pass_mark': 70, 'subject_all': u'music'}] 

And I have to compare a_list to check the pass_mark is higher than pass_list

So the result list would be:

[{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'}, 
{'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'}]

Here is my method :

result_list = []
for a in a_list:
    check = [x for x in pass_list if x['subject_all'] == a['subject']]
    if a['score'] >= check[0]['pass_mark']:
        result_list.append(a)
print result_list

I want to know is there more faster or better method because the a_list will be a large one in the future.


Solution

  • Make a dict where the keys are subjects and the values are scores:

    l = [{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'},
         {'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'},
         {'score': 65, 'credit': 5, 'class': 'B01', 'subject': 'science'},
         {'score': 35, 'credit': 5, 'class': 'C02', 'subject': 'math'}]
    
    l2 = [{'pass_mark': 50, 'subject_all': u'math'},
          {'pass_mark': 70, 'subject_all': u'science'},
          {'pass_mark': 70, 'subject_all': u'music'}]
    
    sub = {dct["subject_all"]: dct["pass_mark"] for dct in l2}
    
    result = [dct for dct in l if dct["score"] >= sub[dct["subject"]]]
    
    print(result)
    

    output:

    [{'credit': 5, 'score': 60, 'class': 'A01', 'subject': 'math'}, {'credit': 5, 'score': 70, 'class': 'A01', 'subject': 'music'}]
    

    You just do one pass over l2 to build the dict, and one pass over l with constant work elsewhere so the solution is O(n) as opposed to your own quadratic approach. Ideally if you could create the sub dict in the first place it would be the best approach.