2015-11-19 30 views
0

所以進出口運行到試圖讓我的字典裏沒有這裏返回任何一個函數中改變一個問題是我的代碼:如何更改函數中的Python字典?

def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons): 
    in_file = open(filename, 'r') 
    emoticons_to_ids = {} 
    ids_to_emoticons = {} 

    for line in in_file: 
     data = line.split() 
     if len(data) > 0: 
      emoticon = data[0].strip('"') 
      id = data[2].strip('"') 
      if emoticon not in emoticons_to_ids: 
       emoticons_to_ids[emoticon] = [] 
      if id not in ids_to_emoticons: 
       ids_to_emoticons[id] = [] 

      emoticons_to_ids[emoticon].append(id) 
      ids_to_emoticons[id].append(emoticon) 

基本上我嘗試做的是在兩個庫傳遞和處理信息的填寫他們從文件工作出來很好,但在我稱之爲主,並嘗試打印兩個字典,它說它們是空的。有任何想法嗎?

+0

這兩行'emoticons_to_ids = {},ids_to_emoticons = {}'會改變什麼,他們指向的參考:

或者,你也可以從函數的最後返回這兩個字典之前到新的,空的字典。這意味着你傳遞給函數的引用(即你稍後在你的代碼中調用的字典)從未被觸及。把這些線看出來,看看會發生什麼 –

+0

這就是訣竅!非常感謝你,我對編碼相當陌生,但我認爲如果我沒有在函數中定義它們中的每一個,那麼代碼會返回一個語法錯誤,說明如何在不被定義的情況下使用它們。 – rngprogramer

+0

只要你通過口授,你應該沒問題 –

回答

1
def load_twitter_dicts_from_file(filename, emoticons_to_ids, ids_to_emoticons): 
    … 
    emoticons_to_ids = {} 
    ids_to_emoticons ={} 

這兩行代替你傳遞給函數的任何東西。所以如果你把兩個字典傳給了這個函數,這些字典是不會被觸及的。相反,您創建了兩個永遠不會傳遞到外部的新字典。

如果您想要將傳遞給該函數的字典進行變異,請刪除這兩行並首先創建字典。

return emoticons_to_ids, ids_to_emoticons