如何在函数外部访问函数内生成的字典,而不必多次调用函数.蟒蛇

HR1*_*23r 1 python dictionary function

我有一个返回字典的函数.

我希望能够在代码中多次访问和使用该字典,而无需每次都调用生成该字典的函数.换句话说,调用函数一次,但使用它返回多次的字典.

所以这样,字典只构造一次(并且可能存储在某个地方?),但在脚本中多次调用和使用.

def function_to_produce_dict():
    dict = {}
    # something
    # something that builds the dictionary 
    return dict 


create_dict = function_to_product_dict()

# other code that will need to work with the create_dict dictionary. 
# without the need to keep constructing it any time that we need it. 
Run Code Online (Sandbox Code Playgroud)

我已阅读其他帖子,例如: 在不使用`global`的情况下访问函数外部的函数变量

但我不确定通过将函数声明为全局而使用function_to_produce_dict()将使字典无需每次构建都可以访问,通过一次又一次地调用该函数.

这可能吗?

Cyp*_*ase 5

也许我不理解,但你已经把它保存了下来create_dict; 继续使用dict in create_dict.一旦你存储它,它不是每次构建的create_dict.

也许你应该重命名它,因为create_dict听起来像一个创建一个字典的函数.也许这与你对此的困惑有关?