Python – 在某些键上比较字典
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要根据选定键的基数比较字典是否相等。这种问题很常见,在很多领域都有应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们对字典进行迭代,并使用来自选定键的相等运算符手动测试键的相等性。
# Python3 code to demonstrate working of
# Compare Dictionaries on certain Keys
# Using loop
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}
test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
# initializing compare keys
comp_keys = ['best', 'geeks']
# Compare Dictionaries on certain Keys
# Using loop
res = True
for key in comp_keys:
if test_dict1.get(key) != test_dict2.get(key):
res = False
break
# printing result
print("Are dictionary equal : " + str(res))
输出 :
The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}
The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}
Are dictionary equal : True
方法 #2:使用all()
这是执行此任务的一种替代方案。在这种情况下,比较功能是使用 all() 完成的,比较所有需要的键。
# Python3 code to demonstrate working of
# Compare Dictionaries on certain Keys
# Using all()
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}
test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
# initializing compare keys
comp_keys = ['best', 'geeks']
# Compare Dictionaries on certain Keys
# Using all()
res = all(test_dict1.get(key) == test_dict2.get(key) for key in comp_keys)
# printing result
print("Are dictionary equal : " + str(res))
输出 :
The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}
The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}
Are dictionary equal : True