Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting all the differences in 2 dictionaries and displaying them all

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.

like image 520
Nate Avatar asked Dec 21 '22 06:12

Nate


1 Answers

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})
like image 86
aldeb Avatar answered Dec 22 '22 20:12

aldeb