Reputation: 41
need help making the function sumcounts(D) where D is a dictionary with numbers as values, returns the sum of all the values. Sample output should be like this:
>>> sumcounts({"a":2.5, "b":7.5, "c":100})
110.0
>>> sumcounts({ })
0
>>> sumcounts(strcount("a a a b"))
4
Upvotes: 2
Views: 3097
Reputation: 3711
The answer as given by Michael above is spot on!
I want to suggest that if you are going to work with large data sets to look at the most excellent Pandas Python Framework.(Maybe overkill for your problem but worth a look)
It accepts dictionaries and transforms it into a data set, for instance
yourdict = {"a":2.5, "b":7.5, "c":100}
dataframe = pandas.Series(yourdict)
You now have a very powerfull data frame that you can realy do a lot of neat stuff on including getting the sum
sum = dateframe.sum()
You can also easily plot it, save it to excel, CSV, get the mean, standard deviation etc...
dateframe.plot() # plots is in matplotlib
dateframe.mean() # gets the mean
dateframe.std() # gets the standard deviation
dataframe.to_csv('name.csv') # writes to csv file
I can realy recomend Pandas. It changed the way I do data business with Python...It compares well with the R data frame by the way.
Upvotes: 1
Reputation: 298344
I'm not sure what you've been taught about dictionaries, so I'll assume the bare minimum.
total
variable and set it to 0
.for x in y
syntax.your_dict[key_name]
.total
.Michael already posted the regular Pythonic solution.
Upvotes: 3
Reputation: 7756
It's already there:
sum(d.values())
Or maybe that:
def sumcount(d):
return sum(d.values())
Upvotes: 8