Python dictionary "addition" and "subtraction"
Python dictionary "addition" and "subtraction"
Posted Mar 15, 2019 23:56 UTC (Fri) by quietbritishjim (subscriber, #114117)In reply to: Python dictionary "addition" and "subtraction" by jani
Parent article: Python dictionary "addition" and "subtraction"
[1] https://docs.python.org/3/library/collections.html#collec...
Posted Mar 17, 2019 11:35 UTC (Sun)
by jani (subscriber, #74547)
[Link] (1 responses)
Posted Mar 20, 2019 20:48 UTC (Wed)
by quietbritishjim (subscriber, #114117)
[Link]
Hmm, it turns out it doesn't work. The obvious thing is to use
This fails for two reasons:
Python dictionary "addition" and "subtraction"
Python dictionary "addition" and "subtraction"
+:
Counter({'a': [1], 'b': [1, 2]}) + Counter({'a': [2, 3], 'b': [3]})
<0 for each element, which fails for lists.
An alternative is to use the update() method, which doesn't have a restriction to positive values so doesn't compare against zero:
c = Counter({'a': [1], 'b': [1, 2]})
c.update(Counter({'a': [2, 3], 'b': [3]}))
But this doesn't work either:
- As with the + operator, missing keys are interpreted as having value 0.
- The values are passed to + in the opposite order than you would expect, so the above example results in
c['a'] == [2,3,1]! This is true in Python 3.7 but not Python 2.7.
I think this is a bug in the documentation, which seems to say that these should be possible (at least for update()), or even a straight up bug in the code. But in fairness it is an unusual use of the class.
