【问题标题】:KeyError when printing dictionary?打印字典时出现KeyError?
【发布时间】:2020-10-28 14:48:19
【问题描述】:

所以我正在尝试编写一个程序,让用户输入课程编号,然后获取该课程的房间、讲师和会议时间信息。如果用户输入的课程未找到/无效,我希望能够打印终止消息,但是当我尝试时,它会出现 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']}")

其他: print(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

【问题讨论】:

    标签: python dictionary input keyerror


    【解决方案1】:

    多个问题:

    首先,您检查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}")
    

    【讨论】:

      【解决方案2】:

      下面的代码应该会让你的生活更轻松。

      它使用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
      

      【讨论】:

      • 这很好用,但现在我很难让它显示“课程详细信息”消息而不打印几次。我想我需要另一种格式化代码结果的方法。
      • 很高兴为您提供帮助。我相信你会解决打印问题。随意投票。
      • 虽然只有代码的答案可能会回答这个问题,但您可以通过为您的代码提供上下文、此代码工作的原因以及一些文档参考以供进一步阅读,从而显着提高您的答案质量.来自How to Answer“简洁是可以接受的,但更全面的解释更好。”
      猜你喜欢
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多