如何在 Python 中将两个字典相乘

在 Python 中将两个字典相乘

How to multiply two dictionaries in Python

使用字典理解来乘以 Python 中的两个字典,例如
result = {key: dict_1[key] * dict_2[key] for key in dict_1}. dict comprehension 遍历字典,我们可以将一个字典的值与另一个字典的相应值相乘。

主程序
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

我们使用字典理解来迭代其中一个字典。

字典理解与列表理解非常相似。

它们对字典中的每一个键值对执行某种操作,或者选择满足条件的键值对的子集。

在每次迭代中,我们从两个字典中访问相同的键并将值相乘。

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.

发表评论