0

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', ] } ] } 

2 Answers 2

3

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() 
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good solution, however, section['class_list'].sort() doesn't treat ids as numbers. You should add a key=int to it.
1

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() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.