Python – Multiplication across Like Keys Value list elements
Last Updated :
09 Apr, 2023
Given two dictionaries with value lists, perform element wise like keys multiplication.
Input : test_dict1 = {“Gfg” : [4, 6], “Best” : [8, 6], “is” : [9, 3]}, test_dict2 = {“Gfg”: [8, 4], “Best” : [6, 3], “is” : [9, 8]} Output : {‘Gfg’: [32, 24], ‘Best’: [48, 18], ‘is’: [81, 24]} Explanation : 4 * 8 = 32, 6 * 4 = 24 and so on, hence new list value. Input : test_dict1 = {“Gfg” : [4, 6], “Best” : [8, 6]}, test_dict2 = {“Gfg”: [8, 4], “Best” : [6, 3]} Output : {‘Gfg’: [32, 24], ‘Best’: [48, 18]} Explanation : 4 * 8 = 32, 6 * 4 = 24 and so on, hence new list value.
Method : Using dictionary comprehension + zip()
This is one of the ways in which this task can be performed. In this, we perform the task of combining keys using zip() and use zip() again for combining like values. The dictionary comprehension is used to perform construction of new list.
Python3
test_dict1 = { "Gfg" : [ 4 , 6 , 7 ], "Best" : [ 8 , 6 , 4 ], "is" : [ 9 , 3 , 4 ]}
test_dict2 = { "Gfg" : [ 8 , 4 , 3 ], "Best" : [ 6 , 3 , 1 ], "is" : [ 9 , 8 , 2 ]}
print ( "The original dictionary 1 is : " + str (test_dict1))
print ( "The original dictionary 2 is : " + str (test_dict2))
res = {key: [ele1 * ele2 for (ele1, ele2) in zip (test_dict1[key], val2)]
for (key, val2) in zip (test_dict1.keys(), test_dict2.values())}
print ( "The constructed dictionary : " + str (res))
|
Output
The original dictionary 1 is : {'Gfg': [4, 6, 7], 'Best': [8, 6, 4], 'is': [9, 3, 4]}
The original dictionary 2 is : {'Gfg': [8, 4, 3], 'Best': [6, 3, 1], 'is': [9, 8, 2]}
The constructed dictionary : {'Gfg': [32, 24, 21], 'Best': [48, 18, 4], 'is': [81, 24, 8]}
Time Complexity: O(n), where n is the elements of dictionary
Auxiliary Space: O(n), where n is the size of dictionary
Method 2: Use a for loop to iterate through the keys and values of the dictionaries:
Python
test_dict1 = { "Gfg" : [ 4 , 6 , 7 ], "Best" : [ 8 , 6 , 4 ], "is" : [ 9 , 3 , 4 ]}
test_dict2 = { "Gfg" : [ 8 , 4 , 3 ], "Best" : [ 6 , 3 , 1 ], "is" : [ 9 , 8 , 2 ]}
print ( "The original dictionary 1 is : " + str (test_dict1))
print ( "The original dictionary 2 is : " + str (test_dict2))
res = {}
for key in test_dict1:
if key in test_dict2:
res[key] = [test_dict1[key][i] * test_dict2[key][i] for i in range ( len (test_dict1[key]))]
print ( "The constructed dictionary : " + str (res))
|
Output
The original dictionary 1 is : {'is': [9, 3, 4], 'Gfg': [4, 6, 7], 'Best': [8, 6, 4]}
The original dictionary 2 is : {'is': [9, 8, 2], 'Gfg': [8, 4, 3], 'Best': [6, 3, 1]}
The constructed dictionary : {'is': [81, 24, 8], 'Gfg': [32, 24, 21], 'Best': [48, 18, 4]}
Time complexity: O(nm), where n is the number of keys in the dictionaries and m is the length of the value lists.
Auxiliary space: O(nm) to store the result dictionary.
Method#3: Using Recursive method.
Algorithm for recursive method:
- Define a recursive function that takes in two dictionaries as arguments.
- Initialize an empty dictionary to store the result.
- Iterate over the keys in the first dictionary.
- Check if the key exists in the second dictionary.
- If the key exists in both dictionaries, multiply the corresponding values of the keys and store the result in the result dictionary.
- If the key does not exist in the second dictionary, store an empty list in the result dictionary for that key.
- Recursively call the function with the remaining keys in both dictionaries.
- Return the result dictionary.
Python3
def multiply_like_keys(dict1, dict2):
res = {}
for key in dict1:
if key in dict2:
if isinstance (dict1[key], list ):
res[key] = [dict1[key][i] * dict2[key][i] for i in range ( len (dict1[key]))]
elif isinstance (dict1[key], dict ):
res[key] = multiply_like_keys(dict1[key], dict2[key])
return res
test_dict1 = { "Gfg" : [ 4 , 6 , 7 ], "Best" : [ 8 , 6 , 4 ], "is" : [ 9 , 3 , 4 ]}
test_dict2 = { "Gfg" : [ 8 , 4 , 3 ], "Best" : [ 6 , 3 , 1 ], "is" : [ 9 , 8 , 2 ]}
res = multiply_like_keys(test_dict1,test_dict2)
print ( "The original dictionary 1 is : " + str (test_dict1))
print ( "The original dictionary 2 is : " + str (test_dict2))
print ( "The constructed dictionary : " + str (res))
|
Output
The original dictionary 1 is : {'Gfg': [4, 6, 7], 'Best': [8, 6, 4], 'is': [9, 3, 4]}
The original dictionary 2 is : {'Gfg': [8, 4, 3], 'Best': [6, 3, 1], 'is': [9, 8, 2]}
The constructed dictionary : {'Gfg': [32, 24, 21], 'Best': [48, 18, 4], 'is': [81, 24, 8]}
The time complexity of the multiply_like_keys() function is O(n^2), where n is the size of the dictionaries dict1 and dict2. This is because the function has to iterate through all the keys in dict1, and for each key, it checks whether it exists in dict2. This requires O(n) time complexity. If the key exists in both dictionaries, the function then checks whether the value for that key is a list or a dictionary. If it is a list, the function multiplies the corresponding elements in both lists using a for loop that iterates through the list, which requires O(n) time complexity. If it is a dictionary, the function calls itself recursively, which requires O(n^2) time complexity because it has to iterate through all the keys in the nested dictionary.
The auxiliary space of the function is also O(n^2), because in the worst case, the function creates a new dictionary for each nested dictionary it encounters. The maximum depth of recursion is equal to the maximum depth of nesting in the dictionaries, which also contributes to the space complexity. The function creates new lists of the same size as the input lists when multiplying them, but this is negligible compared to the space required for the dictionaries.
Method#4: Using numpy:
Algorithm:
- Initialize an empty dictionary “res”.
- Iterate through each key in “dict1”.
- Check if the key is present in “dict2”.
- If the key is present, then check if the value corresponding to the key in “dict1” is a list.
- If the value is a list, then compute the element-wise multiplication of the two lists using numpy and store the
- result in “res” with the same key.
- If the value is a dictionary, then recursively call the function “multiply_like_keys” with the value of the same key in “dict1” and “dict2” and store the result in “res” with the same key.
- Return the resulting dictionary “res”.
Python3
import numpy as np
def multiply_like_keys(dict1, dict2):
res = {}
for key in dict1:
if key in dict2:
if isinstance (dict1[key], list ):
res[key] = list (np.array(dict1[key]) * np.array(dict2[key]))
elif isinstance (dict1[key], dict ):
res[key] = multiply_like_keys(dict1[key], dict2[key])
return res
test_dict1 = { "Gfg" : [ 4 , 6 , 7 ], "Best" : [ 8 , 6 , 4 ], "is" : [ 9 , 3 , 4 ]}
test_dict2 = { "Gfg" : [ 8 , 4 , 3 ], "Best" : [ 6 , 3 , 1 ], "is" : [ 9 , 8 , 2 ]}
res = multiply_like_keys(test_dict1,test_dict2)
print ( "The original dictionary 1 is : " + str (test_dict1))
print ( "The original dictionary 2 is : " + str (test_dict2))
print ( "The constructed dictionary : " + str (res))
|
Output:
The original dictionary 1 is : {'Gfg': [4, 6, 7], 'Best': [8, 6, 4], 'is': [9, 3, 4]}
The original dictionary 2 is : {'Gfg': [8, 4, 3], 'Best': [6, 3, 1], 'is': [9, 8, 2]}
The constructed dictionary : {'Gfg': [32, 24, 21], 'Best': [48, 18, 4], 'is': [81, 24, 8]}
Time Complexity: The time complexity of the function depends on the size of the input dictionaries and the number of nested lists or dictionaries. In the worst case, the function will need to iterate through all the keys in both dictionaries and perform element-wise multiplication of two lists, which takes O(n) time complexity. Therefore, the overall time complexity of the function can be expressed as O(n * k), where “n” is the total number of keys in both dictionaries and “k” is the maximum depth of nested lists or dictionaries.
Space Complexity: The space complexity of the function is also dependent on the size of the input dictionaries and the number of nested lists or dictionaries. In the worst case, the function will need to create a new dictionary “res” with the same number of keys as the input dictionaries and a new list for each nested list that is computed. Therefore, the overall space complexity of the function can be expressed as O(n + m), where “n” is the total number of keys in both dictionaries and “m” is the maximum size of any nested list.
Method#5: Using map() and lambda function to perform element-wise multiplication of list values across dictionaries
Steps:
- Define a lambda function that takes two lists and returns their element-wise product using map() and lambda.
- Use dictionary comprehension to iterate over the keys of one of the dictionaries (test_dict1) and create a new dictionary with the same keys and values equal to the element-wise product of the values of the two dictionaries for that key. Use map() and the lambda function defined in step 1 to perform the element-wise multiplication of the lists.
- Print the resulting dictionary.
Python3
test_dict1 = { "Gfg" : [ 4 , 6 , 7 ], "Best" : [ 8 , 6 , 4 ], "is" : [ 9 , 3 , 4 ]}
test_dict2 = { "Gfg" : [ 8 , 4 , 3 ], "Best" : [ 6 , 3 , 1 ], "is" : [ 9 , 8 , 2 ]}
multiply_lists = lambda x, y: list ( map ( lambda a, b: a * b, x, y))
result_dict = {key: multiply_lists(test_dict1[key], test_dict2[key]) for key in test_dict1}
print ( "The constructed dictionary : " + str (result_dict))
|
Output
The constructed dictionary : {'Gfg': [32, 24, 21], 'Best': [48, 18, 4], 'is': [81, 24, 8]}
Time complexity: O(nk), where n is the number of keys in the dictionaries and k is the length of the lists associated with each key.
Auxiliary space: O(nk), where n is the number of keys in the dictionaries and k is the length of the lists associated with each key.
Similar Reads
Python | Tuple list cross multiplication
Sometimes, while working with Python records, we can have a problem in which we need to perform cross multiplication of list of tuples. This kind of application is popular in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension
5 min read
Python - Multiply all cross list element pairs
Sometimes, while working with Python lists, we can have a problem in which we need to perform the multiplication of each element of list with another list. This can have applications in both web development and day-day programming. Let's discuss certain ways in which this task can be performed. Meth
8 min read
Python | Multiplying Alternate elements in List
The problem of getting product of a list is quite generic and we might some day face the issue of getting the product of alternate elements and get the list of 2 elements containing product of alternate elements. Letâs discuss certain ways in which this can be performed. Method #1 : Using list compr
3 min read
Python - Multiply Consecutive elements in list
While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in
7 min read
Python | Custom Multiplication in list of lists
Sometimes, when we are fed with the list of list, we need to multiply each of its element list with a particular element fed by the order in the other list. This particular problem is very specific but knowledge of it can be useful in such cases. Let's discuss certain ways in which this can be done.
8 min read
Python - Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
3 min read
Python - Constant Multiplication over List
We are given a list we need to multiply each element in the list by a constant. For example, we are having a list a = [1, 2, 3, 4, 5] and constant c=2 we need to multiply this constant in whole list. Using List ComprehensionList comprehension allows us to multiply each element in list by a constant
3 min read
Python - Constant Multiplication to Nth Column
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Letâs discuss certain ways in which K can be multiplied to Nth element of tuple in list. Method #1 : Using loop Using loops this t
7 min read
Python | Multiply each element in a sublist by its index
Given a list of lists, the task is to multiply each element in a sublist by its index and return a summed list. Given below are a few methods to solve the problem. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to multiply numbers with position # and add them to return num
4 min read
Python - Multiply K to every Nth element
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Nth element in list. Letâs discuss certain ways in which this can be perform
5 min read