Write a Python Program to Replace Dictionary Values with their Average

Write a python program to replace dictionary values with their average. is provided on this page.

Write A Python Program To Replace Dictionary Values With Their Average.

In this python program we create a dictionary with three keys and values, the values being numbers so that later we can take average.

Then we get the values using values() method of dictionary object. We then convert it into list using list() function.

After this the sum() is used to find sum of values of keys and we get average by dividing the sum by number of values i.e. number of keys i.e. length of dictionary_values list.

Finally we print dictionary before replacing the value and after replacing the values.


dictionary = {'a' : 10, 'b' : 20, 'c' : 30}
dictionary_values = list(dictionary.values())
average = sum(dictionary_values) / len(dictionary_values)

print("Dictionary before replacing values : ", dictionary)

dictionary = {k : average for k, v in dictionary.items()}

print("Dictionary after replacing value : ", dictionary)

Output

Dictionary before replacing values :  {'a': 10, 'b': 20, 'c': 30}
Dictionary after replacing value :  {'a': 20.0, 'b': 20.0, 'c': 20.0}

Related To Python

Comments