Method # 1: Using vocabulary comprehension + keys()
A combination of the above two can be used to accomplish this particular task. This is just an abbreviation for the longer looping method and can be used to accomplish this task in one line.
# Python3 code to demonstrate how it works Subtraction of dictionaries # Using dictionary comprehension + keys () # Initialize dictionaries test_dict1 = { ’gfg’ : 6 , ’is’ : 4 , ’ best’ : 7 } test_dict2 = { ’gfg’ : 10 , ’ is’ : 6 , ’best’ : 10 } # print original dictionaries print ( "The original dictionary 1: " + str (test_dict1)) print ( "The original dictionary 2:" + str (test_dict2)) # Using dictionary comprehension + keys () Subtracting dictionaries res = {key: test_dict2 [key] - test_dict1.get (key, 0 ) for key in test_dict2.keys ()} # print result print ( " The difference dictionary is: " + str (res)) |
Output:
The original dictionary 1: {’gfg’: 6,’ is’: 4, ’best’: 7} The original dictionary 2: {’ gfg’: 10, ’is’: 6,’ best’: 10} The difference dictionary is: {’gfg’: 4,’ is’: 2, ’best’: 3}
Method # 2: Using Counter ( ) + - operator
A combination of the above method can be used to accomplish this particular task. The Counter function converts the dictionary into a form in which the minus operator can perform the subtraction task.
# Python3 code to demonstrate how it works Subtracting dictionaries # Using Counter () + & quot; - & quot; statement from collections import Counter # Initialize dictionaries test_dict1 = { ’gfg’ : 6 , ’is’ : 4 , ’ best’ : 7 } test_dict2 = { ’ gfg’ : 10 , ’is’ : 6 , ’best’ : 10 } # printing original dictionaries print ( "The original dictionary 1:" + str (test_dict1)) print ( "The original dictionary 2:" + str (test_dict2)) # Using Counter () +" - " statement Subtraction of dictionaries temp1 = Counter (test_dict1) temp2 = Counter (test_dict2) res = temp2 - temp1 # print result print ( "The difference dictionary is:" + str ( dict (res))) |
Output:
The original dictionary 1 : {’gfg’: 6,’ is’: 4, ’best’: 7} The orig inal dictionary 2: {’gfg’: 10,’ is’: 6, ’best’: 10} The difference dictionary is: {’ gfg’: 4, ’is’: 2,’ best’: 3}