2013-07-14 198 views
0

我在我的Python代码和其他几个函数中有一个主函数。在我的主要中,我访问了另一个创建字典的函数。在我的Python代码的末尾是一个将文本写入文本文件的if语句。我无法弄清楚如何访问从前面的函数创建的字典。将字典传递给其他函数

这里是我的代码目前是如何工作的

def main: 
     # "does something" 
     call function X 
     # does other stuff 

    def X: 
     #create dictionary 
     dict = {'item1': 1,'item2': 2} 
     return dictionary 

    .... 
    .... # other functions 
    .... 

    if __name__ == "__main__": 
     # here is where I want to write into my text file 
     f = open('test.txt','w+') 
     main() 
     f.write('line 1: ' + dict[item1]) 
     f.write('line 2: ' + dict[item2]) 
     f.close() 

我刚开始学习Python所以任何帮助是非常赞赏的典范!谢谢!

回答

2

你必须定义函数时加括号(),即使它不带任何参数:

def main(): 
    ... 

def X(): 
    ... 

同时,由于X()回报的东西,你必须分配输出到一个变量。所以,你可以做这样的事情在main

def main(): 
    mydict = X() 
    # You now have access to the dictionary you created in X 

然后,您可以return mydict,如果你想在main(),所以你可以在你的脚本的末尾使用它:

if __name__ == "__main__": 
    f = open('test.txt','w+') 
    output = main() # Notice how we assign the returned item to a variable 
    f.write('line 1: ' + output[item1]) # We refer to the dictionary we just created. 
    f.write('line 2: ' + output[item2]) # Same here 
    f.close() 

你可以不在函数中定义变量,然后在函数的其他地方使用它。该变量只能在相关函数的局部范围内定义。因此,返回它是一个好主意。


顺便说一句,这是不是一个好主意来命名的字典dict。它将覆盖内置。