;

Python Program to Multiply All the Items in a Dictionary


Tutorialsrack 06/05/2020 Python

In this Python program, we will learn how to multiply all the items in a dictionary. In this program, we are using two ways to multiply all the items in a dictionary. The first way is without using any python built-in functions and the second way is using python dictionary built-in values() function.

Here is the source code of the program to multiply all the items in a dictionary.

Program 1: Python Program to Multiply All the Items in a Dictionary Using For Loop

In this program, we used the for loop to multiply all the items. And there is no use of python built-in function.

Python Program to Multiply All the Items in a Dictionary Using For Loop
# Python Program to Multiply All the Items in a Dictionary
# Using For Loop

# Declare a Dictionary
myDict = {'x': 10, 'y':15, 'z':30}

# Print the Dictionary
print("Dictionary: ", myDict)

total = 1

# Multiply Items
for key in myDict:
    total = total * myDict[key]
    
# Print the Output    
print("\nAfter Multiplying Items in the Given Dictionary: ", total)
Output

Dictionary:  {'x': 10, 'y': 15, 'z': 30}

 

After Multiplying Items in the Given Dictionary:  4500

Program 2: Python Program to Multiply All the Items in a Dictionary Using values() function

In this program, we used the for loop to iterate the dictionary and values() to get a list of all the items available in a given list.

Python Program to Multiply All the Items in a Dictionary Using values() function
# Python Program to Multiply All the Items in a Dictionary
# Using values() function

# Declare a Dictionary
myDict = {'x': 10, 'y':15, 'z':30}

# Print the Dictionary
print("Dictionary: ", myDict)

total = 1
# Multiply Items
for i in myDict.values():
    total = total * i
    
# Print the Output     
print("\nAfter Multiplying Items in this Dictionary: ", total)
Output

Dictionary:  {'x': 10, 'y': 15, 'z': 30}

 

After Multiplying Items in this Dictionary:  4500


Related Posts



Comments

Recent Posts
Tags