简体   繁体   中英

KeyError when printing dictionary?

So I am trying to write a program where the user enters the course number and then gets the room, instructor, and meeting times information for that course. I want to be able to print a termination message if the user inputs a course that is not found/valid, but when I try, it comes up with a KeyError. I have tried using a try/except statement, but when I execute the code it comes up with a TypeError.

room_dict = {
    "CS101": {
        "Room": "3004"
    },
    "CS102": {
        "Room": "4501"
    },
    "CS103": {
        "Room": "6755"
    },
    "NT110": {
        "Room": "1244"
    },
    "CM241": {
        "Room": "1411"
    },
}


instructor_dict = {
    "CS101": {
        "Instructor": "Haynes"
    },
    "CS102": {
        "Instructor": "Alvarado"
    },
    "CS103": {
        "Instructor": "Rich"
    },
    "NT110": {
        "Instructor": "Burkes"
    },
    "CM241": {
        "Instructor": "Lee"
    },
}


time_dict = {
    "CS101": {
        "Time": "8:00 a.m."
    },
    "CS102": {
        "Time": "9:00 a.m."
    },
    "CS103": {
        "Time": "10:00 a.m."
    },
    "NT110": {
        "Time": "11:00 a.m."
    },
    "CM241": {
        "Time": "1:00 p.m."
    },
}

courses = {"CS101", "CS102", "CS103", "NT110", "CM241"}
dicts = {'Room':room_dict,'Instructor':instructor_dict,'Time': time_dict}

dash_count = 50
dashes = dash_count * "-"

print(f'College Course Locater Program')
print(f'Enter a course number below to get information')
get_course = input(f'Enter a course number: ')
print(dashes)

course_num = get_course
room = room_dict[get_course]
instructor = instructor_dict[get_course]
time = time_dict[get_course]

if course_num in courses:
    print(f'The details for course {get_course} are: ')
    print(f"Room: {room['Room']}")
    print(f"Time: {time['Time']}")
    print(f"Instructor: {instructor['Instructor']}")

else: print(course_num, 'is an invalid course number.')

Basically, the output I am getting is:

College Course Locater Program
Enter a course number below to get information
Enter a course number: CS # where CS is an invalid course number
--------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Python\Downloads\courseinfo.py", line 75, in <module>
    room = room_dict[get_course]
KeyError: 'CS'

What I am looking for is:

College Course Locater Program
Enter a course number below to get information
Enter a course number: CS
--------------------------------------------------
(course number) is an invalid course number. # where (course number) is an invalid course number

Multiple problems:

First, you check if get_course == room_dict: . But room_dict is the entire dictionary! It can never be equal to the course number you entered.

Second, there's no need to loop for item in room_dict.items(): . Values in a dictionary are supposed to be accessed using their keys . So you'd do something like

get_course = input(f'Enter a course number: ')

print(f'The details for course {get_course} are: ')
room = room_dict[get_course]
instructor = instructor_dict[get_course]
time = time_dict[get_course]
print(f"Room: {room['Room']}, Time: {time['Time']}, Instructor: {instructor['Instructor']}")

Of course, you'd need to make sure get_course exists as a key in all those dictionaries. You can do that by

try:
    room = room_dict[get_course]
    instructor = instructor_dict[get_course]
    time = time_dict[get_course]
except KeyError:
    print("Course info not found")

Even better, you could redefine your dicts so that one single dict contains all the information about the courses.

course_info = {
    "CS101": {
        "Room": "3004",
        "Instructor": "Haynes",
        "Time": "8:00 a.m."
    },
    "CS102": {
        "Room": "4501",
       "Instructor": "Alvarado",
       "Time": "9:00 a.m."
    }
# and so on
}

And then simply do:

get_course = input(f'Enter a course number: ')

try:
    crs = course_info[get_course]
    print(f'The details for course {get_course} are: ')
    print(f"Room: {crs['Room']}, Time: {crs['Time']}, Instructor: {crs['Instructor']}")
except KeyError:
    print(f"Details not found for {get_course}")

The code below should make your life easier.

It uses course_name = 'CM241' for demo purpose only.

room_dict = {
    "CS101": {
        "Room": "3004"
    },
    "CS102": {
        "Room": "4501"
    },
    "CS103": {
        "Room": "6755"
    },
    "NT110": {
        "Room": "1244"
    },
    "CM241": {
        "Room": "1411"
    },
}


instructor_dict = {
    "CS101": {
        "Instructor": "Haynes"
    },
    "CS102": {
        "Instructor": "Alvarado"
    },
    "CS103": {
        "Instructor": "Rich"
    },
    "NT110": {
        "Instructor": "Burkes"
    },
    "CM241": {
        "Instructor": "Lee"
    },
}


time_dict = {
    "CS101": {
        "Time": "8:00 a.m."
    },
    "CS102": {
        "Time": "9:00 a.m."
    },
    "CS103": {
        "Time": "10:00 a.m."
    },
    "NT110": {
        "Time": "11:00 a.m."
    },
    "CM241": {
        "Time": "1:00 p.m."
    },
}

dicts = {'Time':time_dict,'Room':room_dict,'Instructor': instructor_dict}
course_name = 'CM241'
for k,v in dicts.items():
  print(f'{k} --> {v[course_name][k]}')

output

Time --> 1:00 p.m.
Room --> 1411
Instructor --> Lee

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM