簡體   English   中英

將字典傳遞給另一個功能

[英]Passing a dictionary to another function

我已經建立了一個函數來創建字典並返回它。 此函數稱為get_values ,其結構如下:

def initiate_values(directory):
    for file in glob.glob(os.path.join(directory, '*.[xX][lL][sS]')):
        title = os.path.basename(file).lower()
        if title == 'etc.xls':
            wb = xlrd.open_workbook(file)
            wb = wb.sheet_by_name(u'Sheet1')
            get_values(file, wb)    

def get_values():
    info_from_etc = dict()
    # build dict
    return info_from_etc    

它的工作原理是創建字典,然后在我嘗試打印它時打印正確的值。 但是,當我嘗試從另一個函數調用此get_values函數時,字典返回為“ None”。 這是我調用get_values功能-

def packager():
    info_from_etc = initiate_values()
    print info_from_etc # this prints "None"

我在這里做錯了什么,如何在這里返回正確的字典-即不是None的字典。

您需要從initiate_values return字典:

def initiate_values(directory):
    for file in glob.glob(os.path.join(directory, '*.[xX][lL][sS]')):
        title = os.path.basename(file).lower()
        if title == 'etc.xls':
            wb = xlrd.open_workbook(file)
            wb = wb.sheet_by_name(u'Sheet1')
            return get_values(file, wb)  # added `return'
    return {} # or some other value
info_from_etc = initiate_values()

initiate_values不返回任何內容,因此在Python默認情況下,它返回None 您應該能夠根據您想做的事情弄清楚將return語句放在何處。

我同意您確實需要在initiate_values()函數中返回字典,但是您還要在initiate_values函數中給get_values兩個參數(文件,wb),並且在聲明中不給它任何參數。 似乎那里也可能有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM