I have a .txt file with the following lines in it:
23;Pablo;SanJose
45;Rose;Makati
I have this program:
file = open("C:/Users/renato/Desktop/HTML Files/myfile2.txt")
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
else:
file.close()
return {}
id = int(input("Enter the ID of the user: "))
table2 = query(id)
print("ID: "+table2["ID"])
print("Name: "+table2["name"])
print("City: "+table2["city"])
So what's happening (according to me) is:
File is opened
A hash called table
is created and each line of the file is split into 3 keys/values.
If the id
entered by the user matches the value of the key ID
, then close the file
and return the whole hash.
Then, I'm assigning table2
the values on the table
hash and I'm trying to print the values in it.
When I run this, I get the following:
Traceback (most recent call last):
File "C:/Users/renato/Desktop/HTML Files/Python/hash2.py", line 17, in <module>
print("ID: "+table2["ID"])
KeyError: 'ID'
It seems like it's not recognizing the key ID
on the table2
var. I also tried declaring table2
as a hash by putting table2 = {}
before the function is executed, but it continues to display the error message.
How do I assign the values of a returned hash to a variable, so that I can print them using their keys
?
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
Using yield..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With