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
from functools import reduce
from collections import Counter
test_dict = { 70 : [ 7 , 4 , 6 ],
100 : [ 8 , 9 , 5 ],
200 : [ 2 , 5 , 3 , 7 ],
50 : [ 6 , 8 , 5 , 2 ]}
print ( "The original dictionary is : " + str (test_dict))
res = reduce (Counter.__add__, map ( lambda sub: Counter({ele : sub[ 0 ] for ele in sub[ 1 ]}),
test_dict.items()) )
print ( "Extracted Summation dictionary : " + str ( dict (res)))
|
Output
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
test_dict = { 70 : [ 7 , 4 , 6 ], 50 : [ 6 , 8 , 5 , 2 ]}
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
print ( "Extracted Summation dictionary : " + str ( dict (res)))
|
Output
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 list
Auxiliary Space: O(M*N)
M – length of dictionary N – length of each list in value list
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!