複数を組み合わせるにはdefaultdict(Counter)
?
私は2つ持ってdefaultdict(Counter)
いるので、次のことを試しましたが、うまくいきましたが、組み合わせを達成する他の方法はありますか?
>>> from collections import Counter, defaultdict
>>> x = {'a':Counter(['abc','def','abc']), 'b':Counter(['ghi', 'jkl'])}
>>> y = {'a':Counter(['abc','def','mno']), 'c':Counter(['lmn', 'jkl'])}
>>> z = x+y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> z = defaultdict(Counter)
>>> for i in x:
... z[i].update(x[i])
...
>>> for i in y:
... z[i].update(y[i])
...
>>> z
defaultdict(<class 'collections.Counter'>, {'a': Counter({'abc': 3, 'def': 2, 'mno': 1}), 'c': Counter({'jkl': 1, 'lmn': 1}), 'b': Counter({'jkl': 1, 'ghi': 1})})