How to multiply two dictionaries in Python

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Multiply two dictionaries in Python #

Use a dict comprehension to multiply two dictionaries in Python, e.g. result = {key: dict_1[key] * dict_2[key] for key in dict_1}. The dict comprehension iterates over the dictionary where we can multiply the value from one dict with the corresponding value from the other dict.

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

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.

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.

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 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.

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.