Skip to content
Related Articles

Related Articles

Python program to multiply all the items in a dictionary

Improve Article
Save Article
  • Last Updated : 28 Jul, 2022
Improve Article
Save Article

Python program to illustrate multiply all the items in a dictionary could be done by creating a dictionary which 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




# create a dictionary
d = {
    'value1': 5,
    'value2': 4,
    'value3': 3,
    'value4': 2,
    'value5': 1,
}
 
# create a variable to store result
answer = 1
 
# run a loop
for i in d:
    answer = answer*d[i]
 
# print answer
print(answer)

Output

120

Example 2:

Python3




# create a dictionary
d = {
    'a': 10,
    'b': 7,
    'c': 2,
}
 
# create a variable to store result
answer = 1
 
# run a loop
for i in d:
    answer = answer*d[i]
 
# print answer
print(answer)

Output

140

Approach 2: Using values() and list() methods

Python3




# create a dictionary
d = {
    'value1': 5,
    'value2': 4,
    'value3': 3,
    'value4': 2,
    'value5': 1,
}
# create a variable to store result
answer = 1
val=list(d.values())
 
# run a loop
for i in val:
    answer = answer*i
# print answer
print(answer)

Output

120

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!