Davy Kavanagh
Davy Kavanagh

Reputation: 4939

Combining the values in two dictionaries into a list

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

Answers (3)

applicative_functor
applicative_functor

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

phant0m
phant0m

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]}

Explanation

  1. Throw all keys that exist into an anonymous set. (It's a set => no duplicate keys)
  2. For every key, do 3.
  3. For every dictionary d in the list of dictionaries [c1, c2]
    • Check whether the currently being processed key k exists
      • If true: include the expression d[k] in the resulting list
      • If not: proceed with next iteration

Here is a detailed introduction to list comprehension with many examples.

Upvotes: 2

eumiro
eumiro

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

Related Questions