Python - Cumulative Mean of Dictionary keys


When it is required to find the cumulative mean of the dictionary keys, an empty dictionary is created, and the original dictionary is iterated over, and the items are accessed. If this is present in the dictionary, the key is appended to the empty dictionary, otherwise the value is placed instead of the key.

Example

Below is a demonstration of the same

from statistics import mean

my_list = [{'hi' : 24, 'there' : 81, 'how' : 11},
   {'hi' : 16, 'how' : 78, 'doing' : 63}]

print("The list is : ")
print(my_list)

my_result = dict()
for sub in my_list:
   for key, val in sub.items():
      if key in my_result:

         my_result[key].append(val)
      else:
         my_result[key] = [val]

for key, my_val in my_result.items():
   my_result[key] = mean(my_val)

print("The result is : ")
print(my_result)

Output

The list is :
[{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
The result is :
{'hi': 20, 'there': 81, 'how': 44.5, 'doing': 63}

Explanation

  • The required packages are imported.

  • The list of dictionary values is defined, and is displayed on the console.

  • An empty dictionary is defined.

  • The original list of dictionary values is iterated over, and the items are obtained.

  • If this key is present in the dictionary, it is added to the empty dictionary.

  • Otherwise this key is converted into a value.

  • Again the key and values are iterated over, and their mean is obtained using the ‘mean’ method.

  • The output is displayed on the console.

Updated on: 20-Sep-2021

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements