Reputation: 23
I've looked at 10 of these answers and cannot find the answer, maybe I am asking the wrong question but what I am trying to do is take a dictionary created in fileToDict and use it as the parameter of dictValueTotal to add all the values of the dictionary and return that value (which will be used in a third function). Yes, this is indeed homework but I would like to understand it as I am new to python and really don't get how to pass the return value into another function and can't find an answer online or in the book we are using this I don't want to create a class for it as we haven't covered it in class (see what I did there?). Thanks in advance!
Errors being received: First I was getting no global variable 'd' defined so I added the dictionary = fileToDict("words1.txt") line but now I am getting the error TypeError: 'builtin_function_or_method' object is not iterable
Almost forgot my words1.txt looks like this with each string/integer on a separate line: the 231049254
cat 120935
hat 910256
free 10141
one 9503490
we 102930
was 20951
#
going 48012
to 1029401
program 10293012
he 5092309
And this is the code manipulating it:
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()
Upvotes: 2
Views: 616
Reputation: 251355
values
is a method. You need to call it. use dictionary.values()
(note the parentheses), not dictionary.values
.
Upvotes: 5