【发布时间】:2020-06-13 00:20:36
【问题描述】:
一段时间以来,我一直在尝试获取用户输入并将其添加到现有字典中。然后使用 for 循环打印字典键和值,但我无法弄清楚执行此操作的正确方法。
经过研究,我几乎可以肯定我没有正确地将用户输入的值添加到 dict 中,并且当代码运行时,我收到一条错误消息,指出“set”是可下标的。我应该如何将用户数据添加到字典并正确打印?
# Authorized Users
authorized_users = ["Jim","Mary","Claire","Hector","Ren"]
# Student Dictionary
students ={
"Alice":{"id": "1", "age":26, "grade":"A"},
"Bob":{"id": "2", "age":34, "grade":"C"},
"Jimbo":{"id": "3", "age":12, "grade":"B"},
"Karen":{"id": "4", "age":33, "grade":"D"},
"Keith":{"id": "5", "age":53, "grade":"F"}
}
while True:
login = input("Please login with an authorized user: ").strip().title()
if login in authorized_users:
print("\nWelcome back "+login+", please choose an option from the menu!")
print(
'''
1.) View Student List
2.) View Authorized Users
3.) Add student
4.) Remove Student
5.) Exit program
'''
)
authorized_input = int(input("Select an option from the list above to proceed.: "))
if authorized_input == 1:
print("\n*** ACTIVE STUDENTS ***")
for student_id, student_info in students.items():
print("\nName:", student_id)
for key in student_info:
print(key + ':', student_info[key])
print("\n")
elif authorized_input == 2:
print("\n*** AUTHORIZED USERS ***")
for x in range(len(authorized_users)):
print(authorized_users[x])
print("\n")
elif authorized_input == 3:
print("Please fill in the new students information")
student_name = input("Enter the student's name: ")
student_id = input("Enter the student's ID: ")
student_age = input("Enter the student's age: ")
student_grade = input("Enter the student's grade: ")
# Add data to dict students
students[student_name] = {student_id, student_age, student_grade}
for student_id, student_info in students.items():
print("\nName:", student_id)
for key in student_info:
print(key + ':', student_info[key])
print("\n")
elif authorized_input == 4:
print("option 4")
elif authorized_input == 5:
quit()
else:
print("access denied")
【问题讨论】:
标签: python python-3.x list dictionary