Python try-except块未捕获字典KeyError异常的原因排查
问题根因
KeyError未被捕获的核心原因是实际代码的缩进错误:你贴出的代码排版里try块包裹了访问字典的if语句,但本地运行的代码中,if str(course_id) not in student_courses_map[student]:这行不在try块的作用范围内——字典访问操作如果没被try包裹,抛出的KeyError自然不会被后续的except分支接收。
就算缩进正确,这段代码也存在3个会导致运行/逻辑异常的问题:
- 存储类型混乱:except分支中给
student_courses_map[student]赋值的是f-string生成的字符串,但后续逻辑是把这个值当存储course_id的容器做成员判断。字符串的in是子串匹配,和集合/列表的元素匹配逻辑完全不同,会出现大量判断错误,比如存了'1'时,'12' not in '1'返回False、'1' in '12'返回True,完全不符合选课记录的存储需求。 - 赋值逻辑遗漏:except分支里只把单个course_id转成字符串存入字典,没有把已经add了course_id的
student_courses集合同步绑定到字典的对应键,下一次循环读取到的字典值还是字符串,不是预期的集合结构。 - 类型不匹配:
student_courses集合里存的是整数类型的course_id,但成员判断用的是str(course_id)字符串,字符串永远不会和整数集合里的元素相等,判断会恒成立,完全失效。另外别用id当变量名,会覆盖Python内置的id()函数,容易引发难以排查的问题。
修正后代码
直接用字典键存在性判断替代不必要的try-except即可,逻辑更清晰也不容易出错:
student, test_taken = item student_courses_map = {} student_courses = set() for row in tests_df.itertuples(index=False): test_id, course_id, weight = row if test_id in test_taken: # 键不存在时先初始化空集合 if student not in student_courses_map: student_courses_map[student] = set() # 同类型判断成员是否存在 if course_id not in student_courses_map[student]: student_courses.add(course_id) student_courses_map[student] = student_courses
内容的提问来源于stack exchange,提问作者T Affleck
相关产品推荐
相关产品推荐

