Given a dictionary with a values list, where the key represents frequency, compute the total occurrence of each value in values lists.
Input : test_dict = {70 : [7, 4, 6], 50 : [6, 8, 5, 2]}
Output : {7: 70, 4: 70, 6: 120, 8: 50, 5: 50, 2: 50}
Explanation : 6 occurs in both keys, hence 70 + 50 = 120, assigned to 6.Input : test_dict = {70 : [7, 4], 50 : [6, 8, 5, 2]}
Output : {7: 70, 4: 70, 6: 50, 8: 50, 5: 50, 2: 50}
Explanation : 6 now occurs in only 50 key, hence only 50 is assigned.
Method : reduce() + Counter() + lambda + __add__
This is the way in which this task can be performed. In this, Counter() is used to compute the frequency of each value, the summation with keys is done using __add__, all the values from each key are added using reduce(). The map() is used to extend the logic of Counter to each value in the values list.
Python3
# Python3 code to demonstrate working of # Frequency Key Values Summation # Using reduce() + Counter() + lambda + __add__ from functools import reduce from collections import Counter # initializing dictionary test_dict = { 70 : [ 7 , 4 , 6 ], 100 : [ 8 , 9 , 5 ], 200 : [ 2 , 5 , 3 , 7 ], 50 : [ 6 , 8 , 5 , 2 ]} # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Counter() used to get values mapped with keys # __add__ used to add key with values. res = reduce (Counter.__add__, map ( lambda sub: Counter({ele : sub[ 0 ] for ele in sub[ 1 ]}), test_dict.items()) ) # printing result print ( "Extracted Summation dictionary : " + str ( dict (res))) |
The original dictionary is : {70: [7, 4, 6], 100: [8, 9, 5], 200: [2, 5, 3, 7], 50: [6, 8, 5, 2]} Extracted Summation dictionary : {7: 270, 4: 70, 6: 120, 8: 150, 9: 100, 5: 350, 2: 250, 3: 200}
Method: Using nested for loops
- Extract keys and values of dictionary using keys() and values() methods
- Create a dictionary with unique values as keys and keys sum corresponding to values(using list(),set(),nested for loops)
- Display the dictionary
Example
Python3
# Python3 code to demonstrate working of # Frequency Key Values Summation # initializing dictionary test_dict = { 70 : [ 7 , 4 , 6 ], 50 : [ 6 , 8 , 5 , 2 ]} # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) x = list (test_dict.keys()) y = list (test_dict.values()) res = dict () z = [] for i in y: z.extend(i) z = list ( set (z)) for i in z: s = 0 for j in range ( 0 , len (y)): if i in y[j]: s + = x[j] res[i] = s # printing result print ( "Extracted Summation dictionary : " + str ( dict (res))) |
The original dictionary is : {70: [7, 4, 6], 50: [6, 8, 5, 2]} Extracted Summation dictionary : {2: 50, 4: 70, 5: 50, 6: 120, 7: 70, 8: 50}
Time Complexity: O(M*N)
M – length of dictionary N – length of each list in value listAuxiliary Space: O(M*N)
M – length of dictionary N – length of each list in value list