Skip to content

Write a Python program to multiply all the items in a dictionary | Code

  • by

Use for loop and variable to Write a Python program to multiply all the items in a dictionary.

Python program to multiply all the items in a dictionary

A simple example code multiplies all the items in a dictionary. Run a loop to traverse through the dictionary multiply each value of the key with the result and add to the result itself.

my_dict = {'data1': 1, 'data2': -2, 'data3': 3}
res = 1

for key in my_dict:
    res = res * my_dict[key]

print(res)

Output:

Write a Python program to multiply all the items in a dictionary

Another example

d = {
    'a': 10,
    'b': 70,
    'c': 20,
}

# create a variable to store result
answer = 1

for i in d:
    answer = answer * d[i]

print(answer)

Output: 14000

To multiply all the items in a dictionary, you can iterate through the values of the dictionary and perform the multiplication operation. Here’s a Python program to do that:

# Define a dictionary
my_dict = {'a': 2, 'b': 3, 'c': 4, 'd': 5}

# Initialize a variable to store the result
result = 1

# Iterate through the values of the dictionary and multiply them
for value in my_dict.values():
    result *= value

# Print the result
print("The product of all items in the dictionary:", result)

You can replace the my_dict dictionary with your own dictionary containing the items you want to multiply. This program will calculate and print the product of all the values in the dictionary.

Do comment if you have any doubts or suggestions on this Python multiplication topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading