Two python dictionaries may contain some common keys between them. In this article we will find how to get the difference in the keys present in two given dictionaries.
With set
Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second. Those keys which are not common are listed in the result set.
Example
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)
Output
Running the above code gives us the following result −
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'}
Using in with for loop
In another approach we can use a for loop to iterate through the keys of one dictionary and check for its presence using the in clause in the second dictionary.
Example
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)
Output
Running the above code gives us the following result −
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