Reputation: 91
I have a dictionary of length 50 which has numbers(from 0 to 50) as keys and BMI(float from 0.1 to 0.98) as the values.The code that i have tried only extract first and 5th value from the keys..but i need to extract every first and 5th value.
I need to create a new dict such that the output has
key:(0,5), value: average of bmi(first 5 bmi)
key:(6,10), value: average of bmi(next 5 bmi) and so on
key_new=[]
val_new=[]
num=[0,5]
for i in num:
if(i==0):
number=list(dictionary.keys())[i]
key_new.append(number)
elif(i==5):
number=list(dictionary.keys())[i]
key_new.append(number)
print(key_new)
Upvotes: 0
Views: 154
Reputation: 1839
As mentioned in the comments, if your dict keys are numbers 0-50, you should just treat it as a list -> allows you to use list slicing when calculating average.
You can set step=5
in for loop range method.
Example:
bmi_vals = [0.23, 0.24, 0.3, 0.32, 0.16 ...] #Example format for bmi values list
bmi_vals = [your_dictionary[key] for key in range(len(your_dictionary))] #Constructing bmi values list from your dictionary
result = {}
total_size = len(bmi_vals)
step_size = 5
for i in range(0, total_size, step_size):
start_index = i
end_index = i+step_size
result[(start_index , end_index)] = sum(bmi_vals[start_index:end_index])/step_size #Eg Key: Tuple (0, 5), Val: average of first 5
print(result)
You can replace step_size to any other number also -> if you want average of every 10 values then set step_size=10
.
Upvotes: 1