如何组合多个defaultdict(Counter)
?
鉴于我有两个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})})