Multiply the Values in a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Multiply dictionary values by a constant in Python
  2. Multiply all of the values in a Dictionary
  3. Multiply two Dictionaries in Python

# Multiply dictionary values by a constant in Python

To multiply the values in a dictionary by a constant:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a generator expression to iterate over the view and return tuples of key-value pairs.
  3. Pass the result to the dict.update() method.
main.py
import math my_dict = {'a': 2, 'b': 3, 'c': 4} # โœ… multiply dictionary values by number (in place) my_dict.update( (key, value * 2) for key, value in my_dict.items() ) # ๐Ÿ‘‡๏ธ {'a': 4, 'b': 6, 'c': 8} print(my_dict)

multiply dictionary values by constant

The code for this article is available on GitHub

The example multiplies the values of the dictionary by a constant, in place.

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} # ๐Ÿ‘‡๏ธ dict_items([('a', 2), ('b', 3), ('c', 4)]) print(my_dict.items())

We used a generator expression to iterate over the view of items.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we return a tuple containing 2 elements - a key and a value.

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} my_dict.update((key, value * 2) for key, value in my_dict.items()) # ๐Ÿ‘‡๏ธ {'a': 4, 'b': 6, 'c': 8} print(my_dict)

The dict.update method updates the dictionary with the key/value pairs from the provided value.

The method overrides the dictionary's existing keys and returns None.

The dict.update() method can either be called with another dictionary or an iterable of key/value pairs (e.g. a list of tuples with 2 elements each).

# Multiply dictionary values by a constant using a dict comprehension

Alternatively, you can use a dict comprehension to get a new dictionary with the results of the multiplication.

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} new_dict = {key: value * 2 for key, value in my_dict.items()} # ๐Ÿ‘‡๏ธ {'a': 4, 'b': 6, 'c': 8} print(new_dict)

multiply dictionary values by constant using dict comprehension

The code for this article is available on GitHub

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we multiply the current value by 2 and return the key-value pair.

The new dictionary contains the multiplication results and the original dictionary remains unchanged.

# Multiply dictionary values by a constant using a for loop

You can also use a for loop to multiply a dictionary's values by a constant.

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} for key in my_dict: my_dict[key] *= 2 print(my_dict) # ๐Ÿ‘‰๏ธ {'a': 4, 'b': 6, 'c': 8}
The code for this article is available on GitHub

On each iteration, we set the current key to the result of multiplying its value by 2.

# Multiply all of the values in a Dictionary

If you need to multiply all of the values in a dictionary, use the math.prod() method.

main.py
import math my_dict = {'a': 2, 'b': 3, 'c': 4} # ๐Ÿ‘‡๏ธ 24 (same as 2 * 3 * 4) print(math.prod(dict.values(my_dict)))

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} print(my_dict.values()) # ๐Ÿ‘‰๏ธ dict_values([2, 3, 4])

The math.prod() method calculates the product of all the elements in the provided iterable.

main.py
import math my_tuple = (5, 5, 5) result = math.prod(my_tuple) print(result) # ๐Ÿ‘‰๏ธ 125

The method takes the following 2 arguments:

NameDescription
iterableAn iterable whose elements to calculate the product of
startThe start value for the product (defaults to 1)

If the iterable is empty, the start value is returned.

# Multiply all of the values in a Dictionary using a for loop

You can also use a for loop to multiply all of the values in a dictionary.

main.py
my_dict = {'a': 2, 'b': 3, 'c': 4} result = 1 for value in my_dict.values(): result = result * value print(result) # ๐Ÿ‘‰๏ธ 24
The code for this article is available on GitHub

The code sample uses a for loop to iterate over the dictionary's values.

On each iteration, we multiply the current value by the result variable and update its value.

# Multiply two Dictionaries in Python

If you need to multiply two dictionaries, use a dict comprehension.

main.py
dict_1 = { 'a': 2, 'b': 3, 'c': 4, } dict_2 = { 'a': 3, 'b': 4, 'c': 5 } result = {key: dict_1[key] * dict_2[key] for key in dict_1} # ๐Ÿ‘‡๏ธ {'a': 6, 'b': 12, 'c': 20} print(result) print(sum(result.values())) # ๐Ÿ‘‰๏ธ 38
The code for this article is available on GitHub

We used a dict comprehension to iterate over one of the dictionaries.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we access the same key from the two dictionaries and multiply the values.

# Multiply two dictionaries using dict.items()

Alternatively, you can use the dict.items() method to get a view of the dictionary's items.

main.py
dict_1 = { 'a': 2, 'b': 3, 'c': 4, } dict_2 = { 'a': 3, 'b': 4, 'c': 5 } # ๐Ÿ‘‡๏ธ dict_items([('a', 2), ('b', 3), ('c', 4)]) print(dict_1.items()) result = {key: num * dict_2[key] for key, num in dict_1.items()} # ๐Ÿ‘‡๏ธ {'a': 6, 'b': 12, 'c': 20} print(result)

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

On each iteration, we unpack the key and the value from the first dictionary and multiply the value by the corresponding value in the second dictionary.

# Getting the sum of the values in the new Dictionary

If you need to get the sum of the values in the new dictionary, pass the result of calling dict.values() to the sum() function.

main.py
dict_1 = { 'a': 2, 'b': 3, 'c': 4, } dict_2 = { 'a': 3, 'b': 4, 'c': 5 } # ๐Ÿ‘‡๏ธ dict_items([('a', 2), ('b', 3), ('c', 4)]) print(dict_1.items()) result = {key: num * dict_2[key] for key, num in dict_1.items()} # ๐Ÿ‘‡๏ธ {'a': 6, 'b': 12, 'c': 20} print(result) print(result.values()) # ๐Ÿ‘‰๏ธ dict_values([6, 12, 20]) print(sum(result.values())) # ๐Ÿ‘‰๏ธ 38
The code for this article is available on GitHub

The dict.values() method returns a new view of the dictionary's values.

The sum() function takes an iterable, sums its items from left to right and returns the total.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev