Reputation: 4939
In python if I have two dictionaries, specifically Counter objects that look like so
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
Can I combine these dictionaries so that the results is a dictionary of lists, as follows:
c3 = {'item1': [4,6], 'item2':[2,2], 'item3': [5,1], 'item4': [3], 'item5': [9]}
where each value is a list of all the values of the preceding dictionaries from the appropriate key, and where there are no matching keys between the two original dictionaries, a new kew is added that contains a one element list.
Upvotes: 3
Views: 303
Reputation: 4976
You can use defaultdict
:
>>> from collections import Counter, defaultdict
>>> c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
>>> c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
>>> c3 = defaultdict(list)
>>> for c in c1, c2:
... for k, v in c.items():
... c3[k].append(v)
...
>>> c3
defaultdict(<type 'list'>, {'item2': [2, 2], 'item3': [5, 1], 'item1': [4, 6],
'item4': [3], 'item5': [9]})
Upvotes: 1
Reputation: 16905
Or with a list comprehension:
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
merged = {}
for k in set().union(c1, c2):
merged[k] = [d[k] for d in [c1, c2] if k in d]
>>> merged
{'item2': [2, 2], 'item3': [5, 1], 'item1': [4, 6], 'item4': [3], 'item5': [9]}
[c1, c2]
k
exists
d[k]
in the resulting listHere is a detailed introduction to list comprehension with many examples.
Upvotes: 2
Reputation: 212835
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
for k,v in c.iteritems():
c3.setdefault(k, []).append(v)
c3
is now: {'item1': [4, 6], 'item2': [2, 2], 'item3': [5, 1], 'item4': [3], 'item5': [9]}
Upvotes: 8