Python : How to get sum of all values until a specific key is reached in dictionary
Question: I am new to python and have a doubt regarding dictionary operations.  
I am maintaining a dictionary as follows -

    
    
     dict = {counter:distance}.
    

**For example -**

    
    
     dict = {1:1, 2:10, 3:27, 4:10, 5:7, 6:10}
    

For a given key, I wish to find the total distance to reach that key.  
For given key=5, total distance returned should be `(1+10+27+10) = 48.`

I came up with a simple solution as follows -

    
    
    input_key = raw_input()
    dist = 0
    for key,value in dict:
    if key == input_key
        break
    else
        dist += value
    return dist
    

I am looking for some in built function or library that I can use to achieve
this.

My requirement is that I am writing data to an output file. The format is as
follows - docid \t termid \t number 100\t2943\t3

I have for loops which run on each docid and termid. Termid can be repeated in
the loop in which case I need to modify the line in output file. Hence, if
docid 100 and termid 2943 is encoutered again with number as 58, then above
line needs to be changed to - 100\t2943\t3\t58

In this way same line in output file can be modified multiple times based on
docid and termid.

I am looking to reduce time spent in searching the '^docid\ttermid' pattern in
output file and then modifying the line. Hence I plan to maintain a dictionary
which should maintain offset in output file. This way I can loop over the
dictionary and get offset in file, read line and modify the same.


Answer: Dictionary is not an ordered mapping. You need to use other sequence data
structure, or
[`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict)
if you want mapping.

And, iterating over dictionary does not yields key-value pairs, but keys.

Here's a solution that use
[`itertools.takewhile`](https://docs.python.org/2/library/itertools.html#itertools.takewhile):

    
    
    >>> import itertools
    >>> from collections import OrderedDict
    >>>
    >>> d = OrderedDict([(1,1), (2,10), (3,27), (4,10), (5,7), (6,10)])
    >>> print sum(map(d.get, itertools.takewhile(lambda key: key != 5, d)))
    48
    

