I have a dictionary dgr of n (for this example let’s just say n=10) objects named 'gr0' up to 'gr(n-1)' (in case n=10 up to 'gr9') with float values ordered to them in the following fashion:
dgr = {'gr0': 1.3, 'gr1': 1.2, 'gr2': 1.9, 'gr3': 2.4, 'gr4': 2.2, 'gr5': 4.2, 'gr6': 1.2, 'gr7': 5.5, 'gr8': 4.3, 'gr9': 3.2}
I have another dictionary
dy = {}
which is supposed to be filled as such (the 2nd line produces the to-be-fixed error):
for x in range(0,n):
dy["y{0}".format(x)] = sum(dgr.values()[0,x])
so 'y0' is 1.3, but 'y3' is 6.8 so the sum of the values of 'gr0' up to 'gr3'.
Summing all values of gr{x}' (so leaving [0,x] out) works but if I try to do the partial sums with [0,x] it gives me this error:
'dict_values' object is not subscriptable
>Solution :
This might help. I have added n's value to 10(because you start from 0) in the loop you can let it be n though):
for x in range(0,10): # Note: Here n = 10
dy["y{0}".format(x)] = sum(list(dgr.values())[0:x+1])
Output:
{'y0': 1.3, 'y1': 2.5, 'y2': 4.4, 'y3': 6.800000000000001, 'y4': 9.0,
'y5': 13.2, 'y6': 14.399999999999999, 'y7': 19.9, 'y8': 24.2, 'y9': 27.4}
What you were doing wrong?
You cannot subscript dict values. Instead, try to get the values, convert them to a list, and then use slicing.
In slicing, you need to use 0:x+1 otherwise y0 will be 0 and all following keys will have sum till x i.e. 1 key before than intended output. Also, use : (colon) for slicing and not , (commas).