Python字典更新不覆盖问题:为指定教育条目添加多门课程
解决Python中添加多门课程到教育条目时被覆盖的问题
现有两个JSON文件分别存储教育条目与课程信息,需要通过用户输入选择目标教育条目,再循环添加多门课程到该条目下,但原代码使用dict.update()方法时会出现课程被覆盖的问题。
教育条目JSON(edcuations1.json)
{ "itsak22": { "edcuationId": "itsak22", "edcuation_name": "cybersecurityspecialist" }, "feu22": { "edcuationId": "feu22", "edcuation_name": "frontendutvecklare" } }
课程信息JSON(courses1.json)
{ "sql": { "courseId": "itsql", "course_name": "sql", "credits": 35 }, "python": { "courseId": "itpyt", "course_name": "python", "credits": 30 }, "agile": { "courseId": "itagl", "course_name": "agile", "credits": 20 } }
问题根源
原代码中使用first_dicts[first_key]["courses"].update(second_dicts[second_key]),会将选中课程的键值对(如courseId、course_name)直接覆盖到courses字典中——所有课程的顶层键都是重复的,导致每次添加新课程都会替换掉之前的内容,最终只剩最后一门课程的信息。
修改后的代码
import json # 加载教育条目JSON with open('edcuations1.json') as f: first_dicts = json.load(f) # 加载课程信息JSON with open('courses1.json') as f: second_dicts = json.load(f) # 打印可选的教育条目和课程 print("所有教育条目:", first_dicts.keys()) print("所有课程:", second_dicts.keys()) # 选择要添加课程的教育条目 first_key = input("请选择要添加课程的教育条目(输入'q'退出): ") if first_key == 'q': exit() # 循环选择添加课程 while True: second_key = input("请选择要添加的课程(输入'q'退出): ") if second_key == 'q': break # 校验课程是否存在 if second_key not in second_dicts: print(f"课程 {second_key} 不存在,请重新输入") continue # 初始化courses字段(如果不存在) if "courses" not in first_dicts[first_key]: first_dicts[first_key]["courses"] = {} # 以课程标识为键,将整个课程字典存入courses中 first_dicts[first_key]["courses"][second_key] = second_dicts[second_key] # 保存更新后的教育条目JSON with open('edcuations1.json', 'w') as f: json.dump(first_dicts, f, indent=4)
关键修改点
- 替换update方法:将
update()改为直接赋值first_dicts[first_key]["courses"][second_key] = second_dicts[second_key],每门课程以自身标识(如sql、python)作为独立键存入courses字典,避免覆盖。 - 增加课程存在校验:添加
if second_key not in second_dicts判断,防止用户输入不存在的课程导致报错。 - 完善退出逻辑:在选择教育条目时添加
if first_key == 'q': exit(),处理提前退出的场景。
修改后,添加多门课程后的教育条目JSON示例:
{ "itsak22": { "edcuationId": "itsak22", "edcuation_name": "cybersecurityspecialist", "courses": { "sql": { "courseId": "itsql", "course_name": "sql", "credits": 35 }, "python": { "courseId": "itpyt", "course_name": "python", "credits": 30 } } }, "feu22": { "edcuationId": "feu22", "edcuation_name": "frontendutvecklare" } }
内容的提问来源于stack exchange,提问作者user2371684
相关产品推荐
相关产品推荐

