How to return a dictionary | Python -


i have .txt file following lines in it:

23;pablo;sanjose 45;rose;makati 

i have program:

file = open("c:/users/renato/desktop/html files/myfile2.txt")  def query(id):     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 id of user: ")) table2 = query(id) print("id: "+table2["id"]) print("name: "+table2["name"]) print("city: "+table2["city"]) 

so what's happening (according me) is:

file opened hash called table created , each line of file split 3 keys/values. if id entered user matches value of key id, close file , return whole hash.

then, i'm assigning table2 values on table hash , i'm trying print values in it.

when run this, 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 it's not recognizing key id on table2 var. tried declaring table2 hash putting table2 = {} before function executed, continues display error message.

how assign values of returned hash variable, can print them using keys?

what's going on you're returning right after first line of file doesn't match id you're looking for. have this:

def query(id):     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 , return empty dict     file.close()     return {} 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -