0

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])
  • Possible duplicate of [How can I read inputs as integers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers) – Aran-Fey Apr 14 '18 at 09:52

2 Answers2

1

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])
maki
  • 431
  • 3
  • 8
0

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478