Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 202
Andrew Williams Avatar asked Dec 01 '25 02:12

Andrew Williams


2 Answers

It's already there:

sum(d.values())

Or maybe that:

def sumcount(d):
    return sum(d.values())
like image 60
Michael Avatar answered Dec 02 '25 21:12

Michael


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.

like image 22
Blender Avatar answered Dec 02 '25 22:12

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!