如何用Python从student_data字典生成指定格式的课程编码映射字典
Python实现代码
需求1:生成课程对应排序后可用section的字典
实现逻辑:先通过集合自动对section去重,遍历所有学生选课记录后排序,再整理为要求格式。
# 初始化临时字典存储每个课程的section集合(自动去重) course_section_tmp = {} # 遍历所有学生数据 for student in student_data: # 遍历当前学生的所有选课记录 for course_entry in student['enlistment']: code = course_entry['course code'] sec = course_entry['section'] # 课程不存在则初始化空集合 if code not in course_section_tmp: course_section_tmp[code] = set() # 添加section到集合 course_section_tmp[code].add(sec) # 整理为要求的输出格式,section按字母顺序排序 result1 = { code: {"sections": sorted(sec_set)} for code, sec_set in course_section_tmp.items() }
直接打印result1即可得到符合要求的输出。
需求2:生成课程对应section及班级学号列表的字典
实现逻辑:按课程-二级section结构存储对应学号列表,最终整理为要求的数组格式。
# 初始化临时字典,结构为 {课程code: {section: [学号列表]}} course_class_tmp = {} # 遍历所有学生数据 for student in student_data: student_id = student['id'] # 遍历当前学生的所有选课记录 for course_entry in student['enlistment']: code = course_entry['course code'] sec = course_entry['section'] # 课程不存在则初始化空字典 if code not in course_class_tmp: course_class_tmp[code] = {} # section不存在则初始化空列表 if sec not in course_class_tmp[code]: course_class_tmp[code][sec] = [] # 添加当前学生id到对应班级列表 course_class_tmp[code][sec].append(student_id) # 整理为要求的输出格式,section按字母顺序排序 result2 = { code: [ {"section": sec, "class list": id_list} for sec, id_list in sorted(sec_dict.items()) ] for code, sec_dict in course_class_tmp.items() }
直接打印result2即可得到符合要求的输出。
内容的提问来源于stack exchange,提问作者pythonbeginner31
相关产品推荐
相关产品推荐

