Calculate standard deviation of a dictionary in Python
Last Updated :
31 Aug, 2021
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
import numpy as np
dicti = { 'a' : 20 , 'b' : 32 , 'c' : 12 , 'd' : 93 , 'e' : 84 }
listr = []
for value in dicti.values():
listr.append(value)
std = np.std(listr)
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
dicti = { 'a' : 20 , 'b' : 32 , 'c' : 12 , 'd' : 93 , 'e' : 84 }
listr = []
for value in dicti.values():
listr.append(value)
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
import statistics
dicti = { 'a' : 20 , 'b' : 32 , 'c' : 12 , 'd' : 93 , 'e' : 84 }
listr = []
for value in dicti.values():
listr.append(value)
res = statistics.pstdev(listr)
print (res)
|
Output:
33.63569532505609
Share your thoughts in the comments
Please Login to comment...