Reputation:
Python 3 doesn't support this:
dict1 = {key1:6, key2:7, key3:5}
dict2 = {key1:9, key2:3, key3:4}
dict3 = dict1 - dict2
So how how can I subtract dictionary from dictionary in python 3?
Upvotes: 0
Views: 2729
Reputation: 82755
You can use the collections
module.
Ex:
from collections import Counter
dict1 = Counter({"key1":6, "key2":7, "key3":5})
dict2 = Counter({"key1":9, "key2":3, "key3":4})
dict1.subtract(dict2)
print(dict1)
Output:
Counter({'key2': 4, 'key3': 1, 'key1': -3})
Upvotes: 3
Reputation: 25895
You can comprehend it:
>>> dict1 = {'key1':6, 'key2':7, 'key3':5}
>>> dict2 = {'key1':9, 'key2':3, 'key3':4}
>>> dict3 = {key:dict1[key]-dict2[key] for key in dict1}
>>> dict3
{'key2': 4, 'key1': -3, 'key3': 1}
Of course I'm not handling errors:
defaultdict
can solve)Upvotes: 2