How to update list recursively

  • A+
Category:Languages

I have a list of dicts:

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}] 

I want to update the value of each element in this list by the sum of all remainders. (so 'one' will get the value 2+3+4+5) .

so that it will look like this:

a = [{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}] 

'five' is the last, so it will not update .

Im not sure how to achieve this. Im thinking that you construct a function that will call itself recursivly something like:

def recursive(a):    if len(a) == 1:       return list(a[0].values())[0]     else:       val = list(a[0].values())[0]       return val + recursive(a.pop(0)) 

But Im not sure to do this list(a[0].values())[0] is the "best" way. And this is also getting a KeyError: 0.

Any ideas?

 


Iterative and in place solution

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}] sum_so_far = 0 first_flag = False for i in a[::-1]:     k,v = i.items()[0]   #For Python 3 k,v = list(i.items())[0]     sum_so_far += v     if first_flag:         i[k] = sum_so_far # do not change the value at first      first_flag=True 

Output

[{'one': 15}, {'two': 14}, {'three': 12}, {'four': 9}, {'five': 5}] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: