所以我有一个输入,它接受用户输入并使用它来尝试使用键找到正确的字典。它链接到一个.dat文件,它都可以正常工作并找到字典。
如果我只是在运行程序之前输入该位置,就可以了:
print(useraccounts[56443]['forename'])
但是当我使用输入填写“56443”部分时,它将不起作用(称为'id_find'的部分)
id_find = input('Enter the unique student ID: ')
if os.path.exists('useraccounts.dat') == True:
with open('useraccounts.dat', 'rb') as x:
useraccounts = pickle.load(x)
print(useraccounts[56443]['forename'])
print('Student Found: ')
print('\nForename: ', (useraccounts[id_find]['forename']))
print('Second name: ', (useraccounts[id_find]['surname']))
print('DOB: ', (useraccounts[id_find]['dob']))
print('Gender: ', (useraccounts[id_find]['gender']))
print('Username: ', (useraccounts[id_find]['username']))
print('Password: ', (useraccounts[id_find]['password']))
print('Class: ', (useraccounts[id_find]['class']))
这是我回来的。您可以清楚地看到它在运行程序之前找到我输入密钥的字典(George是forename字段),但在使用输入找到它时不起作用。
Enter the unique student ID: 56443
George
Student Found:
Traceback (most recent call last):
File "/Users/admin/Documents/Homework/Computing/spelling bee George Taylor.py", line 335, in <module>
teacher_menu()
File "/Users/admin/Documents/Homework/Computing/spelling bee George Taylor.py", line 224, in teacher_menu
student_edit()
File "/Users/admin/Documents/Homework/Computing/spelling bee George Taylor.py", line 28, in student_edit
print('\nForename: ', (useraccounts[id_find]['forename']))
KeyError: '56443'
提前致谢。
答案 0 :(得分:3)
字典由整数56443键控,您正在使用字符串“56443”进行搜索。
答案 1 :(得分:0)
id_find = input('Enter the unique student ID: ')
更改为:
id_find = int(input('Enter the unique student ID: '))