2013-07-14 196 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。它將覆蓋內置。