[python] How to return a dictionary | Python

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?

This question is related to python python-3.x

The answer is


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 {}

I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.

**Note have used Python 2.7 so some minor modification might be required for Python 3+

class a:
    global d
    d={}
    def get_config(self,x):
        if x=='GENESYS':
            d['host'] = 'host name'
            d['port'] = '15222'
        return d

Calling get_config method using class instance in a separate python file:

from constant import a
class b:
    a().get_config('GENESYS')
    print a().get_config('GENESYS').get('host')
    print a().get_config('GENESYS').get('port')


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..


def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))