I'm trying to access a dictionary at the key where it doesn't exist so I put a try except block around it and add the key during the except. It doesn't catch the KeyError
like it's supposed to. I get a KeyError
during the if statement in my try block. I made a workaround but want to know what is going on here. Sorry if this is not enough to go on let me know if you need more info this is my first post sorry if its bad.
get_test_ids_map()
returns:
{'1': [1, 2, 3, 4, 5, 6, 7], '2': [1, 2, 3, 6, 7], '3': [1, 2, 3, 4, 5, 6, 7]}
student,test_taken = item
student_courses_map = {}
student_courses = set()
for row in tests_df.itertuples(index=False):
id,course_id,weight = row
if id in test_taken:
try:
if str(course_id) not in student_courses_map[student]:
student_courses.add(course_id)
student_courses_map.update({student : student_courses})
except KeyError:
student_courses_map[student] = f'{course_id}'
student_courses.add(course_id)```
I think you can try use element in dict.get(key, [])
to avoid check the KeyError
, like @BeRT2me said. The code will be :
student_courses_map = {}
student_courses = set()
for row in tests_df.itertuples(index=False):
_id,course_id,weight = row
if _id in test_taken:
if str(course_id) not in student_courses_map.get(student,[]):
...
else:
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.