简体   繁体   English

打印字典时出现KeyError?

[英]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.如果用户输入未找到/无效的课程,我希望能够打印终止消息,但是当我尝试时,它会出现 KeyError。 I have tried using a try/except statement, but when I execute the code it comes up with a TypeError.我曾尝试使用 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']}")

else: print(course_num, 'is an invalid course number.') else: print(course_num, '是无效的课程编号。')

Basically, the output I am getting is:基本上,我得到的 output 是:

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: .首先,您检查if get_course == room_dict: But room_dict is the entire dictionary!但是room_dict整个字典! It can never be equal to the course number you entered.它永远不能等于您输入的课程编号。

Second, there's no need to loop for item in room_dict.items(): .其次,不需要循环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.当然,您需要确保get_course作为键存在于所有这些词典中。 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.它使用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]}')

output output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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