📜  Python – 两个字典键的乘积

📅  最后修改于: 2022-05-13 01:55:19.534000             🧑  作者: Mango

Python – 两个字典键的乘积

有时,在使用字典时,我们可能会遇到实用问题,我们需要在字典的公共键之间执行基本操作。这可以扩展到要执行的任何操作。让我们在本文中讨论类似键值的产品和解决方法。

方法#1:使用字典理解+ keys()
以上两者的组合可用于执行此特定任务。这只是较长的循环方法的简写,可用于在一行中执行此任务。

# Python3 code to demonstrate working of
# Dictionary Keys Product
# Using dictionary comprehension + keys()
  
# Initialize dictionaries
test_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}
test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}
  
# printing original dictionaries 
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
  
# Using dictionary comprehension + keys()
# Dictionary Keys Product
res = {key: test_dict2[key] * test_dict1.get(key, 0) 
                       for key in test_dict2.keys()}
  
# printing result 
print("The product dictionary is : " + str(res))
输出 :
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}

方法 #2:使用Counter() + “*”运算符
上述方法的组合可用于执行此特定任务。在此,Counter函数将字典转换为减号运算符可以执行乘法任务的形式。

# Python3 code to demonstrate working of
# Dictionary Keys Product
# Using Counter() + "*" operator
from collections import Counter
  
# Initialize dictionaries
test_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}
test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10}
  
# printing original dictionaries 
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
  
# Using Counter() + "*" operator
# Dictionary Keys Product
temp1 = Counter(test_dict1)
temp2 = Counter(test_dict2)
res = Counter({key : temp1[key] * temp2[key] for key in temp1})
  
# printing result 
print("The product dictionary is : " + str(dict(res)))
输出 :
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}