![]() |
VOOZH | about |
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys.
Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10},
{'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12},
{'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}]
Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5, 'and': 5, 'find': 3}
Explanation : best has 3 values, 10, 8 and 12, their mean computed to 10, hence in result.
Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10},
{'gfg' : 1, 'for' : 10, 'and' : 5, 'best' : 12},
{ 'find' : 3, 'gfg' : 3, 'best' : 8}]
Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'and': 5, 'find': 3}
Explanation : best has 3 values, 10, 8 and 12, their mean computed to 10, hence in result.
Method #1 : Using mean() + loop
In this, for extracting each list loop is used and all the values are summed and memorized using a dictionary. Mean is extracted later by dividing by the occurrence of each key.
Output:
The original list is : [{'gfg': 34, 'is': 8, 'best': 10}, {'gfg': 1, 'for': 10, 'geeks': 9, 'and': 5, 'best': 12}, {'geeks': 8, 'find': 3, 'gfg': 3, 'best': 8}]
The Extracted average : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5, 'and': 5, 'find': 3}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using defaultdict() + mean()
In this, the task of memorizing is done using defaultdict(). This reduces one conditional check and makes the code more concise.
Output:
The original list is : [{'gfg': 34, 'is': 8, 'best': 10}, {'gfg': 1, 'for': 10, 'geeks': 9, 'and': 5, 'best': 12}, {'geeks': 8, 'find': 3, 'gfg': 3, 'best': 8}]
The Extracted average : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5, 'and': 5, 'find': 3}
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #3: Using pandas library
Output:
The Extracted average : {'and': 5.0, 'best': 10.0, 'find': 3.0, 'for': 10.0, 'geeks': 8.5, 'gfg': 12.666666666666666, 'is': 8.0}
Time complexity: O(n*logn), where n is the total number of key-value pairs in the test_list.
Auxiliary space: O(n), where n is the total number of key-value pairs in the test_list.
Method #4: using a list comprehension and the setdefault() method
The Extracted average : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5, 'and': 5, 'find': 3}Time complexity: O(nk), where n is the number of dictionaries in test_list and k is the average number of keys in each dictionary.
Auxiliary space: O(mk), where m is the number of unique keys in all the dictionaries in test_list and k is the average number of values associated with each key.