Open In App

Calculate standard deviation of a dictionary in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing 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


Last Updated : 31 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads