Reputation: 39
This is my code at the moment but I have to sort the sections in alphabetical order and the id numbers in ascending order. Does anyone know where and how I can insert the .sort/.sorted function here?
class_lists = {}
class_sections = {}
for i in student_data:
for j in i['enlistment']:
if j['course code'] not in class_lists.keys():
class_lists[j['course code']] = [{"section":j['section'],'class list':[i['id']]}]
class_sections[j['course code']] = [j['section']]
else:
if j['section'] in class_sections[j['course code']]:
index_ = class_sections[j['course code']].index(j['section'])
class_lists[j['course code']][index_]['class list'].append(i['id'])
else:
class_lists[j['course code']].append({"section":j['section'],'class list':[i['id']]})
class_sections[j['course code']].append(j['section'])
>>> print{class_lists}
{'UK 60': [
{
'section': 'B',
'class list': [
'201007',
'201005',
'211008',
]
},
{
'section': 'A',
'class list': [
'201077',
'201065',
'211088',
]
}
]
}
Upvotes: 0
Views: 90
Reputation: 317
You can sort them this way:
class_lists['UK 60'] = sorted(class_lists['UK 60'], key=lambda item: item['section'])
for section in class_lists['UK 60']:
section['class list'].sort()
Upvotes: 1
Reputation: 71454
Sort all the lists after you've built them rather than trying to do it as you go:
for sections in class_lists.values():
sections.sort(key=lambda s: s['section'])
for section in sections:
section['class_list'].sort()
Upvotes: 3