Home > Net >  How to find the average of the list elements within a dictionary?
How to find the average of the list elements within a dictionary?

Time:12-10

sweets = {'cadbury': [180,90], 'candy': [190],
          'milk chocolate': [150, 160], 'dark chocolate': [100],
          'white chocolate': [180], 'ice cream': [122]}

The dict sweets has different keys and list values pairs. I would like to get your help on finding the average of the numbers in the value list and return the key with the highest average value as output

CodePudding user response:

You can use statistics.mean to compute the mean, and max with a custom key to get the key with a max mean:

sweets = {'cadbury': [180,90], 'candy': [190], 'milk chocolate': [150, 160], 'dark chocolate': [100], 'white chocolate': [180],
 'ice cream': [122]}

from statistics import mean
max(sweets, key=lambda x: mean(sweets[x]))

Output: 'candy'

CodePudding user response:

Using numpy you could try:

d = {x:np.mean(sweets[x]) for x in sweets}

Returning:

{'cadbury': 135.0,
 'candy': 190.0,
 'dark chocolate': 100.0,
 'ice cream': 122.0,
 'milk chocolate': 155.0,
 'white chocolate': 180.0}

And to get the key:

max(d, key=d.get)

Returning:

'candy'

CodePudding user response:

Write a for loop for iterarting every key values in dict. Then write inner loop for calculating average for each key. First have to set maximum average to minimum float value then if value is more than min value set it as maximum average, until loop ends.

  • Related