Merge dicts and create list if duplicate keys

Question:

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?

Asked By: rablentain

||

Answers:

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)
Answered By: cengizkrbck
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.