Related: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
I'd like to merge two string:string dictionaries, and concatenate the values. The above post recommends using collections.Counter
, but it doesn't handle string concatenation.
>>> from collections import Counter
>>> a = Counter({'foo':'bar', 'baz':'bazbaz'})
>>> b = Counter({'foo':'baz'})
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 569, in __add__
TypeError: cannot concatenate 'str' and 'int' objects
(My guess is Counter tries to set b['baz']
to 0.)
I'd like to get a result of {'foo':'barbaz', 'baz':'bazbaz'}
. Concatenation order doesn't matter to me. What is a clean, Pythonic way to do this?