【问题标题】:making a python dictionary accessible inside a function使python字典在函数内部可访问
【发布时间】:2014-03-25 13:49:40
【问题描述】:

我正在构建一个字典,然后我想在函数中访问它。有什么方法可以全局声明所述字典,而不是每次调用 func 时将其传递给函数?

原因是我想调用该函数数百万次,并且我正在尝试使用 p.map() 进行多线程处理,所以我只是想将一行数据传递给我正在调用的函数。 .

def build_dict()
     file=open(f,'r')
     for line in file.readlines():    
            do_something_and_build_dict

def function(data):
     if part_of_data in dict.keys():
           do somthing

results = p.map(function,data) 

谢谢!

【问题讨论】:

  • 不要称它为dict - 这会影响内置
  • 一旦你的字典建成,你的多个线程是否只能只读访问它?

标签: python multithreading function dictionary


【解决方案1】:

您所要做的就是在模块级别(或者可能是类级别,或者适合您使用的任何内容)定义您的字典。只要您不重新分配函数内的字典名称,您就不需要做任何其他事情。

my_dict = {i:i+1 for i in range(10)} # build a module-level dict

def function(data):
    # Do stuff with the global (module-level) dict
    my_dict[2] = data[-1] 
    data.append(my_dict[9])
    return data

if __name__ == '__main__':
    result = function([1,2,3,4,5])
    print(result)
    print(my_dict)

【讨论】:

  • 我不知道为什么,但 'global my_dict' 和我都不起作用。当我尝试访问函数内的字典时,我得到“NameError:未定义全局名称'my_dict'”。我一定是做错了什么……我会检查文档……谢谢你的帮助
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2013-12-03
相关资源
最近更新 更多