Open In App

Python – Multiplication across Like Keys Value list elements

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Multiplication across Like Keys Value list elements
# Using dictionary comprehension + zip()
 
# initializing dictionaries
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]}
 
# printing original lists
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Using zip() to perform link keys and values
res = {key: [ele1 * ele2 for (ele1, ele2) in zip(test_dict1[key], val2)]
       for (key, val2) in zip(test_dict1.keys(), test_dict2.values())}
 
# printing result
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




# Python3 code to demonstrate working of
# Multiplication across Like Keys Value list elements
# Using for loop
 
# initializing dictionaries
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]}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Multiplying the values of the like keys
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]))]
 
# printing result
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:

  1. Define a recursive function that takes in two dictionaries as arguments.
  2. Initialize an empty dictionary to store the result.
  3. Iterate over the keys in the first dictionary.
  4. Check if the key exists in the second dictionary.
  5. If the key exists in both dictionaries, multiply the corresponding values of the keys and store the result in the result dictionary.
  6. If the key does not exist in the second dictionary, store an empty list in the result dictionary for that key.
  7. Recursively call the function with the remaining keys in both dictionaries.
  8. 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
 
# initializing dictionaries
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)
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# printing result
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:

  1. Initialize an empty dictionary “res”.
  2. Iterate through each key in “dict1”.
  3. Check if the key is present in “dict2”.
  4. If the key is present, then check if the value corresponding to the key in “dict1” is a list.
  5. If the value is a list, then compute the element-wise multiplication of the two lists using numpy and store the
  6. result in “res” with the same key.
  7. 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.
  8. 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)
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# printing result
print("The constructed dictionary : " + str(res))
#This code is contributed by Jyothi pinjala


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:

  1. Define a lambda function that takes two lists and returns their element-wise product using map() and lambda.
  2. 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.
  3. Print the resulting dictionary.

Python3




# Python3 code to demonstrate working of
# Multiplication across Like Keys Value list elements
# Using map() and lambda function
 
# initializing dictionaries
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]}
 
# define lambda function for element-wise multiplication of lists
multiply_lists = lambda x, y: list(map(lambda a, b: a*b, x, y))
 
# using dictionary comprehension and map() to perform element-wise multiplication
result_dict = {key: multiply_lists(test_dict1[key], test_dict2[key]) for key in test_dict1}
 
# print result
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.



Last Updated : 09 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads