import json


def form_to_grade_row(form):
    """Creates a grade dict from a row form."""
    course = form['course']
    student = form['student']
    assignment, _, _ = form['assignment'].partition('[')
    rowdata = json.loads(form['rowdata'])
    grade = {'student': student,
             'assignment': assignment,
             'course': course,
             }
    grade['_id'] = '{student}-{assignment}-{course}'.format(**grade)
    scores = {}
    for k, v in rowdata.items():
        if not k.startswith(assignment):
            continue
        _, _, n = k.partition('[')
        n, _, _ = n.partition(']')
        scores[int(n)] = v
    scores = sorted(scores.items())
    grade['scores'] = [v for _, v in scores]
    return grade