Gurken
Gurken

Reputation: 21

Loop over list and increment with values to dictionary

I have a list of this format:

some_list = [[-5, 1000], 
           [0, 600], 
           [50, 600],
           [100,700],
           [170,650],
           [190,700]]

and the function return should be a resulting dict with keys -5, -4, -3 ... and with values as the sum of increments up to each key. so for example above should be -5 : 0 , -4 : 1000, -3 : 2000, -1 : 3000, 0 : 4000, 1 : 4600 and onwards.

Here is some code which is partly working. The problem is the while statement which needs a ceiling to check against and I've therefore added additional items at the end of the list. Assume this can be solved in a much more elegant way. Also the current code exclude last item row of the list due to the break statement.

def framegen(some_list):
    n = 0
    ys = some_list[0][0] 
    frame = []
    xpos = []
    x2 = 0
    for i in some_list:
        while (some_list[n][0]) <= ys < (some_list[(n+1)][0]):
            x1 = ys
            frame.append(x1)
            xpos.append(x2)
            x2 += some_list[n][1]                 
            ys += 1                
            if n == len(some_list) -2 :
                break
        else:
            n += 1        
    temp_dic = dict(zip(frame, xpos))
    dic = {}
    for n in temp_dic:
        dic[n] = temp_dic[n] - temp_dic[0]
    return dic

Edit:

expected output:

   { -5 : 0 , 
-4 : 1000 , 
-3 : 2000 , 
-2 : 3000 , 
-1 : 4000 , 
0 : 5000 , 
1 : 5600 , 
2 : 6200 ,
....}

Upvotes: 2

Views: 381

Answers (1)

CDJB
CDJB

Reputation: 14516

You can do this as follows, iterating over each interval and filling the dictionary based on the previous value.

Code:

some_list = [[-5, 1000], 
           [0, 600], 
           [50, 600],
           [100,700],
           [170,650],
           [190,700]]

d = dict()

for s, e in zip(some_list[:-1], some_list[1:]):
    for k in range(s[0], e[0] + 1):
        if k not in d:
            d[k] = d.get(k-1, -s[1]) + s[1]

Output

>>> d
{-5: 0,
 -4: 1000,
 -3: 2000,
 -2: 3000,
 -1: 4000,
 0: 5000,
 1: 5600,
 2: 6200,
 3: 6800,
 4: 7400,
 ...
 181: 121150,
 182: 121800,
 183: 122450,
 184: 123100,
 185: 123750,
 186: 124400,
 187: 125050,
 188: 125700,
 189: 126350,
 190: 127000}

Upvotes: 1

Related Questions