Python - 字典值部门
有时,在使用字典时,我们可能会遇到实用问题,我们需要在字典的公共键之间执行基本操作。这可以扩展到要执行的任何操作。让我们在本文中讨论相似键值的划分以及解决方法。
方法#1:使用字典理解+ keys()
以上两者的组合可用于执行此特定任务。这只是较长的循环方法的简写,可用于在一行中执行此任务。
# Python3 code to demonstrate working of
# Dictionary Values Division
# Using dictionary comprehension + keys()
# Initialize dictionaries
test_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}
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 Values Division
res = {key: test_dict1[key] // test_dict2.get(key, 0)
for key in test_dict1.keys()}
# printing result
print("The divided dictionary is : " + str(res))
输出 :
The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}
The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}
The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}
方法 #2:使用Counter()
+ “//”运算符
上述方法的组合可用于执行此特定任务。在此,Counter函数将字典转换为除法运算符可以执行除法任务的形式。
# Python3 code to demonstrate working of
# Dictionary Values Division
# Using Counter() + "//" operator
from collections import Counter
# Initialize dictionaries
test_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}
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 Values Division
temp1 = Counter(test_dict1)
temp2 = Counter(test_dict2)
res = Counter({key : temp1[key] // temp2[key] for key in temp1})
# printing result
print("The division dictionary is : " + str(dict(res)))
输出 :
The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}
The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}
The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}