Max average of two dictionaries values in a list Python

Viewed 83

So this is my list of dictionaries:

array_of_dictionaries = [{
    "name": "Budi",
    "age": 23,
    "test_scores": [100.0, 98.0, 89.0]
},
{
    "name": "Charlie",
    "age": 24,
    "test_scores": [90.0, 100.0]
}]

And this is my code:

def get_all_time_max_avg_score(dictionary_list):
  for element in dictionary_list:
    lensum = len(element['test_scores'])
    elesum = sum(element['test_scores'])
    meansum = elesum / lensum
    for attribute in element.keys():
        print("Mr. " + str(element['name']) + " with age(years) " + str(element['age']) + " get the highest average scores, " + str(round(meansum, 2)))
        break
get_all_time_max_avg_score(array_of_dictionaries)

So I want to get the highest average scores from both of that dictionaries. The output I desired is:

Mr. Budi with age(years) 23 get the highest average scores, 95.67

But what I get is:

Mr. Budi with age(years) 23 get the highest average scores, 95.67
Mr. Charlie with age(years) 24 get the highest average scores, 95.0

I really appreciate every help I can get.

5 Answers

This code iterates and prints over every element from your list. Instead, perform max over list by comparing against average.

max(iterable, *, default=None, key=func)

Here's a solution with list comprehension.

def get_all_time_max_avg_score(dictionary_list):
    text = "Mr. {name} with age(years) {age} get the highest average scores, {average:.2f}"

    def average(element):
        return sum(element['test_scores']) / len(element['test_scores'])

    e = max((element for element in dictionary_list), key=average, default=0)
    return text.format(name=e['name'], age=e['age'], average=average(e))


print(get_all_time_max_avg_score(array_of_dictionaries))

Outputs:

Mr. Budi with age(years) 23 get the highest average scores, 95.67

Use the inbuilt max function with a custom key to find out the entry with the highest average score.

array_of_dictionaries = [{
    "name": "Budi",
    "age": 23,
    "test_scores": [100.0, 98.0, 89.0]
},
{
    "name": "Charlie",
    "age": 24,
    "test_scores": [90.0, 100.0]
}]

all_time_max_avg_score = max(
    array_of_dictionaries,
    key=lambda d: sum(d['test_scores']) / len(d['test_scores'])
)
meansum = sum(all_time_max_avg_score['test_scores']) / len(all_time_max_avg_score['test_scores'])

print("Mr. " + str(all_time_max_avg_score['name']) + " with age(years) " + str(all_time_max_avg_score['age']) + " get the highest average scores, " + str(round(meansum, 2)))

You need to compute the mean for each one, before printing anything

def get_all_time_max_avg_score(dictionary_list):
    for element in dictionary_list:
        lensum = len(element['test_scores'])
        elesum = sum(element['test_scores'])
        element['mean'] = elesum / lensum

    first = sorted(dictionary_list, key=lambda x: x['mean'], reverse=True)[0]

    print("Mr.", first['name'], "with age(years)", first['age'], "get the highest average scores,",
          round(first['mean'], 2))

Or using a Dataframe

def get_all_time_max_avg_score(dictionary_list):
    df = pd.DataFrame(dictionary_list)
    df['mean'] = df['test_scores'].apply(np.mean)
    first = df.loc[df['mean'].idxmax()]
    print("Mr.", first['name'], "with age(years)", first['age'],
          "get the highest average scores,", round(first['mean'], 2))

Collect the means from all names and select the max with

def get_all_time_max_avg_score(dictionary_list):
    means = []
    for d in dictionary_list:
        means.append(sum(d['test_scores']) / len(d['test_scores']))
    maxmean = max(means)
    winner = dictionary_list[means.index(maxmean)]
    print(
        f'Mr. {winner["name"]}, with {winner["age"]} years of age, has the ' +
        f'highest average scores: {maxmean:.2f}'
    )


get_all_time_max_avg_score(array_of_dictionaries)

Output

Mr. Budi, with 23 years of age, has the highest average scores: 95.67

With some extra loop you can determine the person who has the max average

def get_all_time_max_avg_score(dictionary_list): 
    maxPersonIndex=0
    maxAver=0
    index=0
    for element in dictionary_list:
        lensum = len(element['test_scores'])
        elesum = sum(element['test_scores'])
        meansum = elesum / lensum
        if(meansum>maxAver):
            maxAver=meansum
            maxPersonIndex=index
        index+=1

            

    for attribute in dictionary_list[maxPersonIndex].keys():
        print("Mr. " + str(element['name']) + " with age(years) " + str(element['age']) + " get the highest average scores, " + str(round(meansum, 2)))
        break
get_all_time_max_avg_score(array_of_dictionaries)
Related