0

I have two dicts in Python which I want to merge. Some of the keys exists in both dicts and I would like them to be in a list in the new dict. Like this:

A = {'item1': 'val1', 'item2': 'val2'}
B = {'item2': 'val3', 'item3': 'val4'}

Should result in this:

{'item1': 'val1', 'item2': ['val2', 'val3'], 'item3': 'val4'}

How do I do that?

rablentain
  • 6,641
  • 13
  • 50
  • 91
  • do you want lists only if there were duplicate keys? – sirlark Oct 14 '14 at 11:50
  • 2
    Wouldn't it make more sense to keep the structure of the new dict consistent as in `{'item1': ['val1'], 'item2': ['val2', 'val3'], 'item3': ['val4']}`? Otherwise, you'd have to wrestle with `isinstance()` and such each time you're accessing the value(s) of the dict, not knowing whether they will be strings or lists... – Tim Pietzcker Oct 14 '14 at 11:50
  • Ok, it might be a better solution to always have lists as values, so, how do i solve the problem? – rablentain Oct 14 '14 at 11:54

1 Answers1

1

Here is some clear code to achieve on efficient way.

import collections

newMap = collections.defaultdict(list)

for key, value in A.iteritems():
    newMap[key].append(value)
cengizkrbck
  • 704
  • 6
  • 21