Search code examples
pythonperformancedictionarysum

Fastest way to sum up in a dictionary with specified (and ordered) keys


What is the fastest way to sum up values in a dictionary, where you need to specify the keys (so not sum the entire values of the dictionary).

For example, let's say I have the following dictionary:

dict_1 = {1: 128, 2: 134, 3: 45, 4: 104, 5: 129}

and I want to sum up the values in keys 3 through 5. In this example, the result is 45+104+129 = 278.

How can I do this as fast as possible?

Here is what I have tried so far:

m = 3
s = 5
summation = 0.
while m <= s:
    summation += dict_1[m]
    m += 1

It works, but I'm looking for a faster way.


Solution

  • Here is another solution (assuming all the keys exist):

    sum(map(dict_1.get, range(3, 5+1)))
    

    This solution is generally faster than the others:

    For the example provided in the question:
     - this solution:   270 ns
     - bb1:             446 ns
     - Gwang-Jin Kim:   356 ns
     - MrGre4a:         244 ns
    
    Dict of 1,000 elements and 20 values fetched:
     - this solution:   526 ns
     - bb1:           36200 ns  (slow because it walks through the whole dict)
     - Gwang-Jin Kim:   965 ns
     - MrGre4a:         879 ns