How to sum the values of a Python dictionary

Friday, May 15th, 2009
Advertisement

Subscribe.
Enter your email:

Suppose that we have a Python dictionary,

x = {'a': 3, 'b': 2, 'c':7}

and, we want to add the values i.e. 3 + 2 + 7 = 12.

Here are the three ways to add the values.

Using list comprehension

>>> x = {'a': 3, 'b': 2, 'c':7}
>>> sum([i for i in x.values()])
12

Using for loop I

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for i in x.values():
    total += i

Using for loop II

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for key in x.keys():
    total += x[key]
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

One Response to “How to sum the values of a Python dictionary”

  1. Matt says:

    Why is list comprehension needed?

    Surely you can just do:


    >>> x = {'a': 3, 'b': 2, 'c':7}
    >>> sum(x.values())
    12

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>