Python - Tuple value product in dictionary


Dictionaries in python are widely used, to store data in key-value pairs. Many times, we get stuck in finding the product of elements in the tuple received as value in the dictionary. This mostly arises in situations working with data manipulation or analysis. Through this article, we will code and understand various ways to unpack the dictionary and calculate the product of tuple elements at each index.

Input

{'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

Output

(4, 36, 150, 392)

Method 1: Using Tuple Unpacking and zip() Function

In this method, we will try to take the tuples from the dictionary and unpack them to get the product. The same index values are grouped together then by zip() and we are able to generate the product of each element in tuples.

Example

# Define a function to calculate the product of elements in a tuple
def prodTup(inp):
   out = 1
   for item in inp:
      out *= item
   return out

# Create a dictionary with tuples as values
inpDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# Print the input dictionary
print("Input Dictionary: " + str(inpDict))

# Calculate the product of elements at the same indices across the tuples
result = tuple(prodTup(ele) for ele in zip(*inpDict.values()))

# Print the calculated products
print("Output: " + str(result))

Output

Input Dictionary: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output: (4, 36, 150, 392)

So we unpacked the dictionary and only the values were kept. Zip helps us to enclose the tuples present as values, the product function thus gets iterated through those enclosed values. The final output is as desired.

Method 2: Using Tuple Unpacking and map() Function

The map function will help us iterate the product function across the tuples. Tuples can be unpacked and arranged such that we can map the product. This can be easily done taking help of loop and list.

Example

# getting Product
def prodTup(inp):
   res = 1
   for ele in inp:
      res *= ele
   return res

# Create a dictionary with tuples as values
inpDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# Print the input dictionary
print("Input Dictionary: " + str(inpDict))

# Using tuple unpacking for transposing
tempList = [list(sub) for sub in inpDict.values()]
transposedTempList = [tuple(row[i] for row in tempList) for i in range(len(tempList[0]))]
result = tuple(map(prodTup, transposedTempList))

# Printing the result
print("Output: ", result)

Output

Input Dictionary: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output:  (4, 36, 150, 392)

So we have used tuple unpacking to get the transposed form so as to correctly map the index elements in the tuples for the product function to be iterated by map. Though the code gets a bit lengthier but can be optimized.

Method 3: Utilizing map(), lambda and reduce()

Let us now try to generate the desired output, but instead of a loop to iterate through the product function we will use map(), lambda that helps us run a function over an iterable. The method reduce() will be for the product function.

Example

import operator
from functools import reduce

def calculatePro(tuples_dict):
   return tuple(map(lambda *args: reduce(operator.mul, args), *tuples_dict.values()))

inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
print("Input list: " + str(inputDict))

result = calculatePro(inputDict)

print("Output: " + str(result))

Output

Input list: {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output: (4, 36, 150, 392)

A simple single line return function actually calculates the product as we see. Map we are passing with lambda, it helps us iterate through each tuple value from the dictionary.

Then the reduce() function can then iterate each element of the tuple index wise through the operator.mul function to get the output.

Method 4: Using List Comprehension and numpy.prod()

List comprehension is used a lot in many problems. Like we had to iterate and unpack the tuples, in the last three methods, list comprehension will help us here. Let us iterate through the tuples at the desired index of the dictionary. The prod method of the numpy library will calculate the product.

Example

import numpy as np

# dictionary with tuples as values
inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}

# the original dictionary
print("Input dictionary: ", inputDict)

result = tuple(np.prod([inputDict[key][i] for key in inputDict]) for i in range(len(inputDict[list(inputDict.keys())[0]])))

# result
print("Output: ", result)

Output

Input dictionary:  {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
Output:  (4, 36, 150, 392)

So we have iterated each index in dictionary values for the tuples. Then we use list and list comprehension to iterate through all the matching indices. Finally, prod gives us the product.

Method 5: Using a Recursive Approach

A recursive approach can also be used to calculate the product of tuple elements at each index. This method can be useful for educational purposes, although it might not be the most efficient for larger datasets.

Example

def prodTup(inp):
   res = 1
   for ele in inp:
      res *= ele
   return res

def recursive_product(tuples_dict, index=0):
   if index >= len(next(iter(tuples_dict.values()))):
      return ()
   return (prodTup(tuple(tuples_dict[key][index] for key in tuples_dict)),) + recursive_product(tuples_dict, index + 1)

inputDict = {'a': (1, 3, 5, 7), 'b': (2, 4, 6, 8), 'c': (2, 3, 5, 7)}
result = recursive_product(inputDict)
print("Output: ", result)

Output

Output:  (4, 36, 150, 392)

Conclusion

Getting the product of tuple elements stored as values in a Python dictionary as per index can be achieved using various methods discussed above. Each method offers its own way of achieving the desired result, providing flexibility and choice based on the specific requirements or boundaries. Hence, always leaving a wide scope for more methods to come in.

It is important to understand the implementation and logic of the approach for each way to iterate through the dictionary values as tuples and then the tuple itself. Mapping the correct index with their values is necessary to achieve the product.

Updated on: 02-Nov-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements