Suppose I have 2 dictionaries:
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Now, I need to print all the difference of these dictionaries and display them all (even if there is a key in A
that is not in B
or otherwise) and of course in absolute values, so the result should be:
c = {'banana':3, 'apple':2, 'pear':5, 'orange':2, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Any ideas? I've seen some posts before but only partial answers to this need.
Using collections.Counter
:
from collections import Counter
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
A_Counter, B_Counter = Counter(A), Counter(B)
print((A_Counter - B_Counter) | (B_Counter - A_Counter))
Output:
Counter({'kiwi': 10, 'pear': 5, 'strawberry': 4, 'banana': 3, 'apple': 2, 'orange': 2, 'blueberry': 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With