user9464508
user9464508

Reputation:

how to subtract dictionary from dictionary with python 3?

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

Answers (2)

Rakesh
Rakesh

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

kabanus
kabanus

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:

  1. Missing keys in dict 2 (defaultdict can solve)
  2. Missing keys in dict 1 (maybe OK?)

Upvotes: 2

Related Questions