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}]
Your problem comes from the output of a.pop(0). A.pop(0) returns the element at 0, not the list without the element at 0. Therefore, when you call recursively, you are indexing on a dict, rather than a list. What do you expect to be inputting into the recursive call?
I would guess you are trying to remove the 0th index, then call recursively. To do this,
a.pop(0);
return val + recursive(a)
edit: a note - key error 0 means you are indexing a dict with key 0 when key 0 does not yet exist.
A possible recursive solution:
d = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
def sums(data, _sum = 0):
a, *b = data
if not b:
return [a], list(a.values())[0]
c, _d = sums(b, _sum+list(a.values())[0])
return [{list(a.keys())[0]:_d}, *c], _d+list(a.values())[0]
result, _ = sums(d)
Output:
[{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With