Product of Values of elements in a Dictionary in Python

A dictionary is a collection of elements with key-value pairs. The values in the elements are accessed with the keys of that element. So let’s start learning: how to find the product of values of elements in a dictionary in Python. One can gain knowledge on the functions and methods of a dictionary by typing

>> help(dict)

in the Python IDLE.

This program emphasizes how to find the product of the integral values of the elements of a dictionary. This can be done by accessing each value using a traversal in for loop and then multiplying them.

Find the product of values in a dictionary in Python

def Product(diction):
     f=diction.values()
     prod=1
     for i in f:
          prod=prod*i
     print(prod)
d={'Monday':12,'Tuesday':15,'Wednesday':45}
Product(d)

 OUTPUT:

8100

CODE EXPLANATION:

We are considering a parameter diction. Later, during function call, this parameter is replaced by a global variable to which a dictionary is assigned. For eg: In the above code, we use a variable diction and then replace the parameter by d while calling Product(). This is done after declaring a dictionary to variable d.  A user-defined function named Product is used to obtain the desired output.

  1. As a first step, we used a variable f allocated in memory and assigned a list to it.
  2. The dict.values() method of a dictionary form a list of the values of the elements in the dictionary. For eg: if there is a dictionary        d={‘A’:1,’B’:2,’C’:3, ’D’:4,’E’:5} then the method d.values() generates a list of the values of the elements which would be [1,2,3,4,5].
    You may read: Creating A Dictionary From A String In Python
  3. A variable prod is allocated to a memory space. It is initialized with 1.
  4. Using a for loop, one can traverse the list allocated to variable f.
  5. Then every single element of the list is multiplied to the variable called prod.
  6. The variable prod calculates the product of the values of the dictionary elements is then printed.

Applications:


Now that you have gone through the above part of an article, what do you think can act as an application to this program? As difficult as you think, one of the easiest applications would be factorial of a number. For eg: You have to find the factorial of a number 5.

  1. A list of the numbers upto 6 can be made using the function: range(1,6).
  2. Using the above program, we can find the factorial now.

Leave a Reply

Your email address will not be published. Required fields are marked *