Merge dictionaries retaining values for duplicate keys
duplicates, merge, python
Solution
def merge_dicts(*dicts):
d = {}
for dict in dicts:
for key in dict:
try:
d[key].append(dict[key])
except KeyError:
d[key] = [dict[key]]
return d
This retuns:
{'a': [1, 5], 'b': [2, 4], 'c': [3], 'd': [6]}
There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:
for key in d:
if len(d[key]) == 1:
d[key] = d[key][0]
before the `return d` statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)
Problem
Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys. Example: ``` d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'b': 4} d3 = {'a': 5, 'd': 6} ``` result: ``` >>> newdict {'c': 3, 'd': 6, 'a': [1, 5], 'b': [2, 4]} ``` My code so far: ``` >>> def merge_dicts(*dicts): ... x = [] ... for item in dicts: ... x.append(item) ... return x ... >>> merge_dicts(d1, d2, d3) [{'a': 1, 'b': 2}, {'c': 3, 'b': 4}, {'a': 5, 'd': 6}] ``` What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?