How to sum all the values in a dictionary?

前端 未结 9 1938
一生所求
一生所求 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:00

    I feel sum(d.values()) is the most efficient way to get the sum.

    You can also try the reduce function to calculate the sum along with a lambda expression:

    reduce(lambda x,y:x+y,d.values())
    

提交回复
热议问题