打印字典时出现KeyError吗?

时间:2020-10-28 14:48:19

标签: python dictionary input keyerror

因此,我正在尝试编写一个程序,用户在该程序中输入课程号,然后获取该课程的会议室,讲师和会议时间信息。如果用户输入未找到/有效的课程,我希望能够打印终止消息,但是当我尝试时,它会提示KeyError。 我曾尝试使用try / except语句,但是执行代码时会出现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']}")

其他: 打印(course_num,'是无效的课程号。)

基本上,我得到的输出是:

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'

我正在寻找的是:

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

2 个答案:

答案 0 :(得分:3)

多个问题:

首先,您检查if get_course == room_dict:。但是room_dict是整个词典!它永远不能等于您输入的课程号。

第二,无需循环for item in room_dict.items():。字典中的值应该使用其进行访问。所以你会做类似的事情

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']}")

当然,您需要确保get_course作为所有这些字典的键存在。您可以通过

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

更好的是,您可以重新定义字典,以便一个字典包含有关课程的所有信息。

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
}

然后简单地做:

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}")

答案 1 :(得分:1)

下面的代码应使您的生活更轻松。

它仅将course_name = 'CM241'用于演示。

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]}')

输出

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