How to find mean of a value array inside a dict in Python?

I have a Dict item like this:

{'XYZ': [30.34, 27.46, 28.49, 22.35, 24.73, 33.96, 31.18, 30.0, 40.17, 38.22, 33.76, 21.28, 24.63, 27.47, 22.85, 20.45, 6.5, 0.56, 0.97, -7.64, 12.73, 10.69, 9.43, -32.22, -35.82, 16.92, 11.77, 4.16, 28.79, 19.65, 36.54, 34.31, 49.43, 37.18, 32.89, 22.99]}

I have 2 questions;

a. I want to check if each of the first 5 values in the value array you see above are all higher than 11. If yes, I want the XYZ to be added to a new dict.

b. I want to check if the mean of the first 5 values in the value array you see above is higher than 11. If yes, I want to add XYZ AND the mean value as a dict.

And in each case, if values are unavailable or are negative, I should ignore it.

Can you please guide me through this? As the value of my dict is an array, I did not know the efficient way to handle this.

Thanks!

Answer

Try like this:

d={'XYZ': [30.34, 27.46, 28.49, 22.35, 24.73, 33.96, 31.18, 30.0, 40.17, 38.22, 33.76, 21.28, 24.63, 27.47, 22.85, 20.45, 6.5, 0.56, 0.97, -7.64, 12.73, 10.69, 9.43, -32.22, -35.82, 16.92, 11.77, 4.16, 28.79, 19.65, 36.54, 34.31, 49.43, 37.18, 32.89, 22.99]}
new_dict = {}
if all(x>11 for x in d['XYZ'][:5]):
  new_dict['XYZ'] = d['XYZ']
elif [sum(d['XYZ'][:5])/5 for x in d['XYZ'][:5]][0]>11:
  new_dict['XYZ'] = sum(d['XYZ'][:5])/5

print(new_dict)

Try it online!

List slicing can be done get first n elements, then all() and generator expression to check first condition sum()/5 to get average