Safin Mahmud
Safin Mahmud

Reputation: 17

Python: key error for using user input as dict key

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

Answers (2)

maki
maki

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

Thomas
Thomas

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

Related Questions