使用collections.defaultdict
:
In [38]: a = {"this" : 2 , "is" : 3}
In [39]: b = {"what" : 3 , "is" : 2}
In [40]: from collections import defaultdict
In [41]: collected_counter=defaultdict(list)
In [42]: for key,val in a.items():
collected_counter[key].append(val)
....:
In [43]: for key,val in b.items():
collected_counter[key].append(val)
....:
In [44]: collected_counter
Out[44]: defaultdict(<type 'list'>, {'this': [2], 'is': [3, 2], 'what': [3]})
アップデート:
>>> keys=a.viewkeys() | b.viewkeys()
>>> collected_counter=defaultdict(list)
>>> for key in keys:
collected_counter[key].append( a.get(key,0) )
...
>>> for key in keys:
collected_counter[key].append( b.get(key,0) )
...
>>> collected_counter
defaultdict(<type 'list'>, {'this': [2, 0], 'is': [3, 2], 'what': [0, 3]})