How to sum the values of a Python dictionary

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]

Related

This entry was posted in Python and tagged , , , . Bookmark the permalink.

3 Responses 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

  2. kjg says:

    x.values() creates list itsefl.
    Be more pro – use dict builtin iteration:
    >>> x = {‘a’: 3, ‘b’: 2, ‘c’:7}
    >>> sum(x.itervalues())
    12

  3. Selinap says:

    @kjg: In Python 3, ‘dict’ object has no attribute ‘itervalues’ anymore. values() returns a lightweight set-like object, effectively making it behave like the old iter* methods.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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