Reputation: 45
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?
Upvotes: 0
Views: 211
Reputation: 11615
You never return your dictionary in read_ticker
, and it's unclear why you're calling the function twice.
Where print(c)
is put return c
.
And I think you want to index the dict instead of indexing the input.
Also, what is c
that you're indexing with? This is undefined. I'm assuming this is meant to be the dictionary as defined in read_ticker
. In which case you want d[x]
.
The dictionary c
isn't global, although you could define it to be, so you can't access it in your other function by c
(ignoring that the indexing is backwards even if possible). Instead, since the dictionary is local to the function read_ticker
and modified there we return the dictionary and store it in the variable d
.
Upvotes: 1
Reputation: 2172
Your ticker function can use get, which allows you to give a value if the key doesn't exist, like this:
def ticker():
x = input('Ticker: ')
return d.get(x, "No entry")
Upvotes: 0
Reputation: 613
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'
Upvotes: 0