Finding the average value in a Python dictionary can be very useful for data analysis and processing. In Python, a dictionary is a built-in data type that allows for the storage of key-value pairs.
These pairs can hold a versatile range of data which can be strings, integers, floating numbers, or other Python objects. In this tutorial, we will show you how you can easily find the average in a Python Dictionary.
Step 1: Create a Python Dictionary
First, we need to have a Python dictionary. Let’s assume we have a dictionary where keys are student names and values are their grades:
1 2 3 4 5 6 7 |
student_grades = { 'Jack': 85, 'Jill': 78, 'Steve': 92, 'Anna': 87, 'Leo': 95, } |
Step 2: Calculate the Average
Then, we will calculate the average grade. Python’s built-in sum() function will sum up all the dictionary values. We divide this total by the count of the items, which we get with the built-in len() function:
1 |
average = sum(student_grades.values()) / len(student_grades) |
Step 3: Output the Result
Lastly, we will print the average:
1 |
print('The average grade is:', average) |
The expected output will be:
The average grade is: 87.4
Full Code
Here is the complete Python code we have used:
1 2 3 4 5 6 7 8 9 10 |
student_grades = { 'Jack': 85, 'Jill': 78, 'Steve': 92, 'Anna': 87, 'Leo': 95, } average = sum(student_grades.values()) / len(student_grades) print('The average grade is:', average) |
The average grade is: 87.4
Conclusion
In this tutorial, we learned how to calculate the average of dictionary values in Python. The simplicity of Python’s syntax along with powerful built-in functions for statistical calculations makes it a great language for data processing and analysis.
Keep practicing with different kinds of data and continue exploring Python’s vast capabilities for handling data.