简体   繁体   中英

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?

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 .

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'

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM