将字典传递给另一个函数

2024-05-08 17:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我构建了一个函数来创建字典并返回它。此函数称为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-

^{pr2}$

我在这里做了什么不正确的事情,我如何在这里返回正确的字典——也就是说,不是None的字典。在


Tags: path函数frominfoget字典titleos
3条回答

您需要return来自initiate_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')
            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两个参数(file,wb),并且在声明中没有给它任何参数。似乎那里也有问题。在

相关问题 更多 >