📜  Python - 字典中不等项的频率

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

Python - 字典中不等项的频率

有时,在使用Python时,我们可能会遇到一个问题,即我们需要检查两个字典之间的不相等项目数。这在 Web 开发和其他领域也有应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用字典理解
这个特定的任务可以使用字典理解在一行中执行,它提供了一种压缩冗长的粗暴逻辑的方法,只检查不相等的项目和增加计数。

# Python3 code to demonstrate working of
# Dissimilar items frequency in Dictionary
# 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))
  
# Dissimilar items frequency in Dictionary
# Using dictionary comprehension
res = {key: test_dict1[key] for key in test_dict1 if key not in test_dict2}
  
# printing result
print("The number of uncommon items are : " + str(len(res)))
输出 :
The original dictionary 1 is : {'best': 3, 'is': 2, 'gfg': 1}
The original dictionary 2 is : {'good': 3, 'is': 2, 'gfg': 1}
The number of uncommon items are : 1

方法 #2:使用set() + XOR运算符+ items()
上述方法的组合可用于执行此特定任务。在此,set函数删除重复项,XOR运算符计算匹配项。可以通过减去原始字典来计算结果。新字典的长度。长度。

# Python3 code to demonstrate working of
# Dissimilar items frequency in Dictionary
# 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))
  
# Dissimilar items frequency in Dictionary
# Using set() + XOR operator + items()
res = set(test_dict1.items()) ^ set(test_dict2.items())
  
# printing result
print("The number of uncommon items are : " + str(len(test_dict1) - len(res)))
输出 :
The original dictionary 1 is : {'best': 3, 'is': 2, 'gfg': 1}
The original dictionary 2 is : {'good': 3, 'is': 2, 'gfg': 1}
The number of uncommon items are : 1