Create list of items based on average-most values and use in later block

Hello! I have a task in which participants see 20 images (various flowers) and rate how much they like each image on a scale from 1-5 (using a slider). My goal is to find the 4 images with ratings closest to the average value, then use these 4 images as stims for a task later on.

I have written the following function to find the 4 average-most images:

###stimSelection - (Begin Experiment)###
flower_rating_list =
def get_4_closest_to_avg(rating_list, avg):
dist_from_avg_dict = dict()
for rating in rating_list:
flower = rating_list.index(rating) + 1
if rating >= avg:
dist_from_avg = rating - avg
dist_from_avg_dict[flower] = dist_from_avg
else:
dist_from_avg = avg - rating
dist_from_avg_dict[flower] = dist_from_avg
output =
for _ in range(4):
if dist_from_avg_dict:
rating = min(dist_from_avg_dict.values())
flower = [key for key in dist_from_avg_dict if dist_from_avg_dict[key] == rating]
output += flower
del dist_from_avg_dict[flower[0]]
return output

###stimSelection - (End Routine)###
#note each marker position on slider
flwrRating = flowerRating.markerPos
#add each rating
flower_rating_list.append(flwrRating)

Once all 20 images have been displayed, this code is supposed to identify the 4 average-most stims:
###break1 - (Begin Routine)###
#find average rating of all flowers
#record average to data file
flower_average_rating = np.mean(flower_rating_list)
currentLoop.addData(‘flowerRateValue’, flower_average_rating)

four_flowers = get_4_closest_to_avg(flower_rating_list, flower_average_rating)
currentLoop.addData(‘four_flowers’, four_flowers)

#lowest possible distance for each stim in the list
for flower in four_flowers:
idx = four_flowers.index(flower)
#needs f in front of index to make 4 separate columns in excel file
currentLoop.addData(f’flower {idx}', flowerFile)

The issue I’m running into - the code is correctly creating four columns (flower 0, flower 1, etc.), but the same value (the lastmost value) is populating into each column. It seems that something in the code is overwriting the other values. flowerFile comes from a spreadsheet of image names (“01.png” and so on), and the code is correctly drawing the file name as opposed to the trial name.

I’m also unsure of how to get these 4 values into a list/index/array of some sort to be used as stims for the task later in the experiment. Thank you for your help!