How to sum all the values in a dictionary?

前端 未结 9 1793
一生所求
一生所求 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 01:53

    In Python 2 you can avoid making a temporary copy of all the values by using the itervalues() dictionary method, which returns an iterator of the dictionary's keys:

    sum(d.itervalues())
    

    In Python 3 you can just use d.values() because that method was changed to do that (and itervalues() was removed since it was no longer needed).

    To make it easier to write version independent code which always iterates over the values of the dictionary's keys, a utility function can be helpful:

    import sys
    
    def itervalues(d):
        return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())
    
    sum(itervalues(d))
    

    This is essentially what Benjamin Peterson's six module does.

    0 讨论(0)
  • 2020-11-28 01:54

    You could consider 'for loop' for this:

      d = {'data': 100, 'data2': 200, 'data3': 500}
      total = 0
      for i in d.values():
            total += i
    

    total = 800

    0 讨论(0)
  • 2020-11-28 01:55
    d = {'key1': 1,'key2': 14,'key3': 47}
    sum1 = sum(d[item] for item in d)
    print(sum1)
    

    you can do it using the for loop

    0 讨论(0)
  • 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())
    
    0 讨论(0)
  • 2020-11-28 02:02

    sum(d.values()) - "d" -> Your dictionary Variable

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

    You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

    Example:

    c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}
    
    sum(list(c.values()))
    
    0 讨论(0)
提交回复
热议问题