( ) collections.Counter ( ) :
In [1]: from collections import Counter
In [2]: d1 = {'red':10, 'blue':20, 'green':30, 'yellow':40}
...: d2 = {'red':1, 'blue':2, 'green':3}
...:
In [3]: A = Counter(d1)
In [4]: B = Counter(d2)
In [5]: A - B
Out[5]: Counter({'blue': 18, 'green': 27, 'red': 9, 'yellow': 40})
@WillemVanOnsem,
", d2 , d1, , : , ".
, Counter, substract() ( python 3.2), Counter ( dict.update():
In [26]: A = Counter({'red':10, 'blue':20, 'green':30, 'yellow':40})
...: B = Counter({'red':1, 'blue':30, 'green':3})
...:
In [27]: A - B
Out[27]: Counter({'green': 27, 'red': 9, 'yellow': 40})
In [28]: A.subtract(B)
In [29]: A
Out[29]: Counter({'blue': -10, 'green': 27, 'red': 9, 'yellow': 40})
The main goal collections.Counteris, in particular, counting / saving the occurrences of hashed objects (thus, accepting values that are natural numbers), but basically it is a subclass of dict that provide several operations for combining objects Counterbetween them (addition, subtraction, union and intersection )
source
share