Python|字典中的常用项
有时,在使用Python时,我们可能会遇到一个问题,即我们需要检查两个字典中的相同项目数。这在 Web 开发和其他领域也有应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用字典理解
这个特定的任务可以使用字典理解在一行中执行,它提供了一种压缩冗长的粗暴逻辑的方法,只检查相等的项目和增加计数。
# Python3 code to demonstrate the working of
# Equal items among dictionaries
# Using dictionary comprehension
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'gfg' : 1, 'is' : 2, 'good' : 3}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Equal items among dictionaries
# Using dictionary comprehension
res = {key: test_dict1[key] for key in test_dict1 if
key in test_dict2 and test_dict1[key] == test_dict2[key]}
# printing result
print("The number of common items are : " + str(len(res)))
输出 :
The original dictionary 1 is : {'gfg': 1, 'best': 3, 'is': 2}
The original dictionary 2 is : {'gfg': 1, 'is': 2, 'good': 3}
The number of common items are : 2
方法 #2:使用set()
+ XOR运算符+ items()
上述方法的组合可用于执行此特定任务。在此, set
函数删除重复项,XOR运算符计算匹配项。
# Python3 code to demonstrate working of
# Equal items among dictionaries
# Using set() + XOR operator + items()
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'gfg' : 1, 'is' : 2, 'good' : 3}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Equal items among dictionaries
# Using set() + XOR operator + items()
res = set(test_dict1.items()) ^ set(test_dict2.items())
# printing result
print("The number of common items are : " + str(len(res)))
输出 :
The original dictionary 1 is : {'gfg': 1, 'best': 3, 'is': 2}
The original dictionary 2 is : {'gfg': 1, 'is': 2, 'good': 3}
The number of common items are : 2