This seems okay, if a little bit code-golfy:
{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})}
If you want to stick with the defaultdict
output, you could simplify things into one loop with itertools.chain
:
z = defaultdict(Counter)
for k,v in chain(x.iteritems(), y.iteritems()):
z[k].update(v)