Reputation: 39
I need to create a dictionary whose keys are unique course codes and whose values are dictionaries with a single key-value pair describing the sections available for that course code, in alphabetical order.
The data is from a dictionary called student_data that looks like this:
student_data[:3]
>>>[{'enlistment': [{'course code': 'UK 60', 'section': 'A'},
{'course code': 'GF 24', 'section': 'B'},
{'course code': 'ME 40', 'section': 'B'},
{'course code': 'VY 44', 'section': 'D'},
{'course code': 'EN 94', 'section': 'B'}],
'id': '201001', 'paid': True, 'school': 'SOSE', 'year level': 2},
{'enlistment': [{'course code': 'EQ 61', 'section': 'D'},
{'course code': 'UZ 22', 'section': 'B'},
{'course code': 'KS 36', 'section': 'B'},
{'course code': 'VH 63', 'section': 'A'},
{'course code': 'IW 81', 'section': 'C'}],
'id': '211002', 'paid': True, 'school': 'JGSOM', 'year level': 1},
{'enlistment': [{'course code': 'WE 15', 'section': 'D'},
{'course code': 'ZP 68', 'section': 'A'},
{'course code': 'GI 78', 'section': 'A'},
{'course code': 'GK 72', 'section': 'C'},
{'course code': 'FA 24', 'section': 'D'},
{'course code': 'UJ 28', 'section': 'A'}],
'id': '201003', 'paid': True, 'school': 'JGSOM', 'year level': 2}]
Format of the desired output:
{
course_code: {
"sections": [sections]
}
}
I've been trying to do this but I don't have a good grasp of dictionaries in Python so I've been having a difficult time. Please help.
EDIT: What if I have to get the ID numbers per section as well?
Format of the desired output with ID numbers:
{
course_code: [{
"section": section_letter,
"class list": [id_numbers]
}]
}
Upvotes: 0
Views: 54
Reputation: 26
I'm not sure that understood you correctly, but maybe it should be something like this:
data = {}
for i in student_data:
for j in i['enlistment']:
if j['course code'] not in data:
data[j['course code']] = {'sections':[j['section']]}
else:
data[j['course code']]['sections'].append(j['section'])
for i in data.keys():
data[i]['sections'] = sorted(data[i]['sections'])
Upvotes: 1