Reputation: 17
When I am taking a user input of the num variable, I am getting a key error. But if I assign a value to that variable, then it's working fine. Why am I getting a key error for taking a user input of the key?
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
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])
Upvotes: 0
Views: 1125
Reputation: 431
The input is read as a string, while on your use case (when working), num is an integer. Just convert the string to integer:
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
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])
Upvotes: 1
Reputation: 182000
This is happening because the user input is a string (str
), whereas the actual key in the dictionary is an integer (int
). Try converting it to an integer first:
num = int(input('Search by ETEXT NO:'))
As an aside, you don't need to use a dictionary if you're just looking things up by index. A regular list is easier and faster.
Upvotes: 0