VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-values-mean/

⇱ Python - Dictionary Values Mean - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Dictionary Values Mean

Last Updated : 5 Jun, 2023

Given a dictionary, find the mean of all the values present.

Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} 
Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. 

Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15} 
Output : 10.0 
Explanation : Mean of these is 10.0

Method #1 : Using loop + len()

This is a brute way in which this task can be performed. In this, we loop through each value and perform summation and then the result is divided by total keys extracted using len().


Output
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(1) constant additional space required

Method #2 : Using sum() + len() + values()

The combination of above functions can be used to solve this problem. In this, we perform summation using sum() and size() of total keys computed using len().


Output
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

Method #3 : Using values() and mean() method of statistics module


Output
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7

Method 4:Using the reduce function from the functools library

Using reduce function to calculate the sum of values and then dividing by the length of the dictionary

Approach:

  1. Import the reduce function from the functools library
  2. Define a function accumulate to take two arguments x and y, and return their sum (i.e., x+y)
  3. Use the reduce function to apply the accumulate function to all the values of the dictionary to get their sum
  4. Divide the sum by the length of the dictionary to get the mean
  5. Return the mean

Output
Mean: 7.0

Time complexity: O(n)
Space complexity: O(1)

Method 5:using the NumPy module

Approach:

  1. Import the NumPy module.
  2. Convert the dictionary values to a NumPy array.
  3. Use the NumPy mean() function to compute the mean of the array.
  4. Print the computed mean.

Output

The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

Time complexity:

Converting dictionary values to a NumPy array takes O(n) time, where n is the number of values in the dictionary.
Computing the mean using the NumPy mean() function takes O(1) time.
Therefore, the overall time complexity is O(n).
Auxiliary space complexity:

Converting dictionary values to a NumPy array requires O(n) auxiliary space.
Computing the mean using the NumPy mean() function requires O(1) auxiliary space.
Therefore, the overall auxiliary space complexity is O(n).

Comment