How to sum all the values in a dictionary?

前端 未结 9 1786
一生所求
一生所求 2020-11-28 01:39

Let\'s say I have a dictionary in which the keys map to integers like:

d = {\'key1\': 1,\'key2\': 14,\'key3\': 47}

Is there a syntactically

相关标签:
9条回答
  • 2020-11-28 02:09

    Sure there is. Here is a way to sum the values of a dictionary.

    >>> d = {'key1':1,'key2':14,'key3':47}
    >>> sum(d.values())
    62
    
    0 讨论(0)
  • 2020-11-28 02:09

    phihag's answer (and similar ones) won't work in python3.

    For python 3:

    d = {'key1': 1,'key2': 14,'key3': 47}
    sum(list(d.values()))
    

    Update! There are complains that it doesn't work! I just attach a screenshot from my terminal. Could be some mismatch in versions etc.

    0 讨论(0)
  • 2020-11-28 02:15

    As you'd expect:

    sum(d.values())
    
    0 讨论(0)
提交回复
热议问题