如何合并多个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})})
答案 0 :(得分:4)
这似乎没关系,如果有点代码 - 高尔夫球:
{k:(x.get(k,Counter()) + y.get(k,Counter())) for k in (x.keys()+y.keys())}
Out[23]:
{'a': Counter({'abc': 3, 'def': 2, 'mno': 1}),
'b': Counter({'jkl': 1, 'ghi': 1}),
'c': Counter({'jkl': 1, 'lmn': 1})}
如果您想坚持defaultdict
输出,可以使用itertools.chain
简化为一个循环:
z = defaultdict(Counter)
for k,v in chain(x.iteritems(), y.iteritems()):
z[k].update(v)