Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find average score of each students from dictionary of scores
When working with student scores stored in a dictionary, calculating the average score for each student is a common task. In Python, we can achieve this by iterating through the dictionary and computing the mean of each student's scores.
So, if the input is like scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}, then the output will be [38.25, 68.75, 50.25, 49.25] where 38.25 is average score for Amal, 68.75 is average score for Bimal and so on.
Algorithm
To solve this, we will follow these steps ?
- Create an empty dictionary avg_scores to store results
- For each student name in the scores dictionary, do
- Calculate average by dividing sum of scores by count of scores
- Store the result in avg_scores[name]
- Return list of all average values
Example
Let us see the following implementation to get better understanding ?
def solve(scores):
avg_scores = dict()
for name in scores:
avg_scores[name] = sum(scores[name]) / len(scores[name])
return list(avg_scores.values())
scores = {'Amal': [25,36,47,45], 'Bimal': [85,74,69,47], 'Tarun': [65,35,87,14], 'Akash': [74,12,36,75]}
print(solve(scores))
[38.25, 68.75, 50.25, 49.25]
Using Dictionary Comprehension
We can also solve this more concisely using dictionary comprehension ?
def solve_compact(scores):
avg_scores = {name: sum(score_list) / len(score_list) for name, score_list in scores.items()}
return list(avg_scores.values())
scores = {'Amal': [25,36,47,45], 'Bimal': [85,74,69,47], 'Tarun': [65,35,87,14], 'Akash': [74,12,36,75]}
print(solve_compact(scores))
[38.25, 68.75, 50.25, 49.25]
Conclusion
Both approaches effectively calculate student averages from a dictionary of scores. The dictionary comprehension method provides a more concise solution, while the traditional loop offers better readability for beginners.
