Regis_ Regis_ - 6 months ago 21
Python Question

Printing a dictionary value of a function in another function

I'm trying to write a looping function that prompts the user to enter a key from the first function and if it is is a key then it prints its value. If the word entered is not in the dictionary it returns "No entry".

What I have so far.

def read_ticker():
c = {}
with open('tickers.csv') as f:
for line in f:
items = [item.strip('"').strip() for item in line.split(",")]
c[items[0]] = items[1:]

print(c)

read_ticker()

d = read_ticker()

def ticker():

x = input('Ticker: ')
if x in d:
return x[c]
else:
return 'No entry'
ticker()


How can I return the value of the key entered in the second function?

Answer

Your read_ticker() function should return c:

def read_ticker():
    c = {}
    with open('tickers.csv') as f:
        for line in f:
            items = [item.strip('"').strip() for item in line.split(",")]
            c[items[0]] = items[1:]

    print(c)
    return c

and then you can modify your ticker function as follows:

def ticker():
    x = input('Ticker: ')
    if x in d.keys():
        return d[x]
    else:
        return 'No entry'
Comments