I have the following in my database in an object called “item” and I want to write some python that will select the lowest score from each group of student_id….I am a total python noob…how would I do this?
{u'student_id': 197, u'_id': ObjectId('50906d7fa3c412bb040eb88d'), u'type': u'homework', u'score': 10.90872422518918}
{u'student_id': 197, u'_id': ObjectId('50906d7fa3c412bb040eb88e'), u'type': u'homework', u'score': 88.3871242475841}
{u'student_id': 198, u'_id': ObjectId('50906d7fa3c412bb040eb892'), u'type': u'homework', u'score': 17.46279901047208}
{u'student_id': 198, u'_id': ObjectId('50906d7fa3c412bb040eb891'), u'type': u'homework', u'score': 76.18366499496366}
{u'student_id': 199, u'_id': ObjectId('50906d7fa3c412bb040eb895'), u'type': u'homework', u'score': 49.34223066136407}
{u'student_id': 199, u'_id': ObjectId('50906d7fa3c412bb040eb896'), u'type': u'homework', u'score': 58.09608083191365}
UPDATE:
having some trouble running my code…can I get some sanity checking done? I’m getting this error…
NameError: name 'getResultFromDatabase' is not defined
Thank you for your trouble….here is my code…
import pymongo
from itertools import groupby
from pymongo import Connection
data = getResultFromDatabase()
connection = Connection('localhost', 27017)
db = connection.students
item = db.grades.find({'type' : 'homework'}).sort([('student_id',pymongo.ASCENDING),('score',pymongo.ASCENDING)])
for id, items in groupby(data, lambda s: s['student_id']):
lowest_score = min(i['score'] for i in items)
print lowest_score
groupbydoes what you want: