Open In App

Python – Dictionary Values Mean

Last Updated : 05 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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().

Python3




# Python3 code to demonstrate working of 
# Dictionary Values Mean
# Using loop + len()
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# loop to sum all values 
res = 0
for val in test_dict.values():
    res += val
  
# using len() to get total keys for mean computation
res = res / len(test_dict)
  
# printing result 
print("The computed mean : " + str(res)) 


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().

Python3




# Python3 code to demonstrate working of 
# Dictionary Values Mean
# Using sum() + len() + values()
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values extracted using values()
# one-liner solution to problem.
res = sum(test_dict.values()) / len(test_dict)
  
# printing result 
print("The computed mean : " + str(res))


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

Python3




# Python3 code to demonstrate working of
# Dictionary Values Mean
  
import statistics
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res=statistics.mean(list(test_dict.values()))
  
# printing result
print("The computed mean : " + str(res))


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

Python3




from functools import reduce
  
def accumulate(x, y):
    return x + y
  
def dict_mean(d):
    values_sum = reduce(accumulate, d.values())
    mean = values_sum / len(d)
    return mean
  
# Example usage
d = {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
print("Mean:", dict_mean(d))


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.

Python3




import numpy as np
   
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 7, "Best" : 8,
             "for" : 6, "Geeks" : 10}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
   
# Using numpy.mean() to compute mean of dictionary values
res = np.mean(list(test_dict.values()))
   
# printing result
print("The computed mean : " + str(res))


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).



Similar Reads

Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
Python - Inner Nested Value List Mean in Dictionary
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The
5 min read