Andrew Williams
Andrew Williams

Reputation: 41

Return the sum of all values in a dictionary Python

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

Answers (3)

Tooblippe
Tooblippe

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

Blender
Blender

Reputation: 298344

I'm not sure what you've been taught about dictionaries, so I'll assume the bare minimum.

  1. Create a total variable and set it to 0.
  2. Iterate over all keys in your dictionary using the normal for x in y syntax.
  3. For every key, fetch its respective value from your dictionary using your_dict[key_name].
  4. Add that value to total.
  5. Get an A on your assignment.

Michael already posted the regular Pythonic solution.

Upvotes: 3

Michael
Michael

Reputation: 7756

It's already there:

sum(d.values())

Or maybe that:

def sumcount(d):
    return sum(d.values())

Upvotes: 8

Related Questions