Skip to content
Related Articles

Related Articles

Improve Article
Calculate standard deviation of a dictionary in Python
  • Last Updated : 01 Nov, 2020

Python dictionary is a versatile data structure that allows a lot of operations to be done without any hassle. Calculating the standard deviation is shown below.

Example #1: Using numpy.std()

First, we create a dictionary. Then we store all the values in a list by iterating over it. After this using the NumPy we calculate the standard deviation of the list.

Python3




# imporitng numpy
import numpy as np
      
# creating our test dictionary
dicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84}
      
# declaring an empty list
listr = []
      
# appending all the values in the list
for value in dicti.values():
    listr.append(value)
          
# calculating standard deviation using np.std
std = np.std(listr)
      
# printing results
print(std)

Output: 



33.63569532505609  

Example #2: Using list comprehension

First, we create a list of values from the dictionary using a loop. Then we calculate mean, variance and then the standard deviation.

Python3




# creating our test dictionary
dicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84}
  
# declaring an empty list
listr = []
  
# appending all the values in the list
for value in dicti.values():
    listr.append(value)
  
# Standard deviation of list
# Using sum() + list comprehension
mean = sum(listr) / len(listr)
variance = sum([((x - mean) ** 2) for x in listr]) / len(listr)
res = variance ** 0.5
print(res)

Output: 

33.63569532505609  

Example #3: Using pstdev()

Pythons inbuilt statistics library provides a function to compute the standard deviation of a given list.

Python3




# importing the module
import statistics
  
# creating the test dictionary
dicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84}
  
# declaring an empty list
listr = []
  
# appending all the values in the list
for value in dicti.values():
    listr.append(value)
  
# Standard deviation of list
# Using pstdev()
res = statistics.pstdev(listr)
print(res)

Output

33.63569532505609

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :