2013-03-13 51 views
2

我已經看了這些答案中的10個,並且找不到答案,也許我問的是錯誤的問題,但是我想要做的是以fileToDict創建的字典和使用它作爲dictValueTotal的參數來添加字典的所有值並返回該值(將在第三個函數中使用該值)。是的,這確實是家庭作業,但我想了解它,因爲我是新的python,真的不知道如何將返回值傳遞到另一個函數,並且無法在線或在我們正在使用的書中找到答案我不想爲它創建一個類,因爲我們沒有在課堂上講過它(請參閱我在那裏做了什麼?)。提前致謝!傳遞一個返回語句作爲另一個函數的參數

收到的錯誤:首先,我沒有定義全局變量'd',所以我添加了dictionary = fileToDict(「words1.txt」)行,但現在我得到錯誤TypeError:'builtin_function_or_method'對象不可迭代

差點忘了我words1.txt看起來是這個樣子的每個字符串/整數在單獨一行: 的231049254

cat 120935 
hat 910256 
free 10141 

one 9503490 
we 102930 
was 20951 
# 

going 48012 
to 1029401 
program 10293012 
    he 5092309 

這是代碼操縱它:

import sys 

def dictValueTotal (dictionary): 
    """dictValueTotal takes in a dictionary and outputs the sum of all the values of the different keys in the input dictionary""" 
    valueTotal = sum(dictionary.values) 
    return valueTotal 


def fileToDict (inFile): 
    """takes a name of a file as input and outputs a dictionary containing the contents of that file""" 
    fileIn = open(inFile, "r")   #Open a file 
    d = {}       #create a dictionary 
    for line in fileIn: 
      line = line.strip()   #remove whitespace 
      if line == "":    #disregard empty strings 
        continue 
      if line[0] == '#':   #disregard lines starting with # 
        continue 
      print line     #debugging purposes 
      line = line.split()   #remove duplicated spaces 
      print line     #debugging purposes 
      line[1] = int(line[1]) 
      print line     #debugging purposes 
      key = line[0] 
      value = line[1] 
      d[key] = value 
    print d 
    return d 
def main(): 
    fileToDict("words1.txt") 
    dictionary = fileToDict("words1.txt") 
    dictValueTotal(dictionary) 


main() 

回答

5

values是一種方法。你需要調用它。使用dictionary.values()(注意括號),而不是dictionary.values

+0

完美的非常感謝你!我想知道爲什麼它不起作用,因爲我這樣做的方式和我在課堂上教過的方式非常讚賞BrenBarn – 2013-03-13 23:58:16

相關問題