两个python词典之间可能包含一些通用键。在本文中,我们将找到如何获得两个给定字典中存在的键的差异。
在这里,我们采用两个字典并将集合函数应用于它们。然后,我们减去两组以得到差值。我们通过两种方式做到这一点,即从第一个字典减去第二个字典,然后从第二个字典减去第二个字典。结果集中列出了那些不常见的键。
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'} print("1st Distionary:\n",dictA) dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'} print("1st Distionary:\n",dictB) res1 = set(dictA) - set(dictB) res2 = set(dictB) - set(dictA) print("\nThe difference in keys between both the dictionaries:") print(res1,res2)
输出结果
运行上面的代码给我们以下结果-
1st Distionary: {'1': 'Mon', '2': 'Tue', '3': 'Wed'} 1st Distionary: {'3': 'Wed', '4': 'Thu', '5': 'Fri'} The difference in keys between both the dictionaries: {'2', '1'} {'4', '5'}
在另一种方法中,我们可以使用for循环遍历一个字典的键,并使用第二个字典中的in子句检查其是否存在。
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'} print("1st Distionary:\n",dictA) dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'} print("1st Distionary:\n",dictB) print("\nThe keys in 1st dictionary but not in the second:") for key in dictA.keys(): if not key in dictB: print(key)
输出结果
运行上面的代码给我们以下结果-
1st Distionary: {'1': 'Mon', '2': 'Tue', '3': 'Wed'} 1st Distionary: {'3': 'Wed', '4': 'Thu', '5': 'Fri'} The keys in 1st dictionary but not in the second: 1 2