当我获取 num 变量的用户输入时,我收到一个键错误。但是如果我为该变量分配一个值,那么它就可以正常工作。为什么我在获取用户输入的密钥时收到密钥错误?
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('nn')
etextDict = {}
x = len(bookList)
for book in bookList:
etextDict[x] = book
x -= 1
num = input('Search by ETEXT NO:')
print(etextDict[num])
num=1
print(etextDict[num])
输入被读取为字符串,而在您的用例中(工作时(,num 是一个整数。只需将字符串转换为整数:
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('nn')
etextDict = {}
x = len(bookList)
for book in bookList:
etextDict[x] = book
x -= 1
num = input('Search by ETEXT NO:')
print(etextDict[int(num)]) # <- changed this line
num=1
print(etextDict[num])
这是因为用户输入是一个字符串(str
(,而字典中的实际键是一个整数(int
(。首先尝试将其转换为整数:
num = int(input('Search by ETEXT NO:'))
顺便说一句,如果您只是按索引查找内容,则无需使用字典。常规列表更容易、更快捷。