Python program to multiply all the items in a dictionary
Last Updated :
17 Apr, 2023
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable.
Example:
Input: dict = {‘value1’:5, ‘value2’:4, ‘value3’:3, ‘value4’:2, ‘value5’:1}
Output: ans = 120
Input: dict = {‘v1’:10, ‘v2’:7, ‘v3’:2}
Output: ans = 140
Approach 1:
- Create a dictionary d and store key-value pairs in it.
- Create a variable answer initialized to 1.
- Run a loop to traverse through the dictionary d
- Multiply each value of key with answer and store the result in answer itself.
- Print answer.
Below are the examples of above approach.
Example 1:
Python3
d = {
'value1' : 5 ,
'value2' : 4 ,
'value3' : 3 ,
'value4' : 2 ,
'value5' : 1 ,
}
answer = 1
for i in d:
answer = answer * d[i]
print (answer)
|
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(1), as only a single variable is used to store the result.
Example 2:
Python3
d = {
'a' : 10 ,
'b' : 7 ,
'c' : 2 ,
}
answer = 1
for i in d:
answer = answer * d[i]
print (answer)
|
Approach 2: Using values() and list() methods
Python3
d = {
'value1' : 5 ,
'value2' : 4 ,
'value3' : 3 ,
'value4' : 2 ,
'value5' : 1 ,
}
answer = 1
val = list (d.values())
for i in val:
answer = answer * i
print (answer)
|
Time Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary Space Complexity: O(1), as the amount of additional space used is constant regardless of the size of the input.
Approach 3: Using functools.reduce(), operator.mul
Python3
d = {
'value1' : 5 ,
'value2' : 4 ,
'value3' : 3 ,
'value4' : 2 ,
'value5' : 1 ,
}
answer = 1
val = list (d.values())
from functools import reduce
import operator
print ( reduce (operator.mul,val, 1 ))
|
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.
Share your thoughts in the comments
Please Login to comment...