Mohsin Khalid
Mohsin Khalid

Reputation: 51

Merging mulit-valued dictionaries

Lets say I have two dictionaries with multiple values per key:

Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}

I want to merge them into one dictionary like this:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }

Upvotes: 0

Views: 73

Answers (3)

zipa
zipa

Reputation: 27869

This should do it, and covers possibity of Dict1 having keys that Dict2 doesn't:

Dict1 = {'key1': ['value1', 'value2'], 'key3': ['value7', 'value8']}
Dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5', 'value6']}

mergedDict = {k: [0, 0] + v  if k not in Dict1 else Dict1[k] + v for k, v in Dict2.items()}
mergedDict.update({i: j + [0, 0] for i, j in Dict1.items() if i not in Dict2})
#{'key3': ['value7', 'value8', 0, 0], 'key2': [0, 0, 'value5', 'value6'], 'key1': ['value1', 'value2', 'value3', 'value4']}

Upvotes: 1

Tiny.D
Tiny.D

Reputation: 6556

Try with defaultdict:

from collections import defaultdict
dict1  = { 'key1' : ['value1','value2'] }
dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5','value6']}
dict3 = defaultdict(list)
for d1, d2 in dict1.items() + dict2.items():
    dict3[d1].extend(d2)
dict(dict3) #convert defaultdict to dict

Output:

{'key1': ['value1', 'value2', 'value3', 'value4'],
 'key2': ['value5', 'value6']}

Upvotes: 0

timgeb
timgeb

Reputation: 78690

Loop over the union of the keys and use dict.get with the default value [0, 0].

>>> dict1 = {'key1' : [1, 2]}
>>> dict2 = {'key1' : [3, 4], 'key2' : [5, 6]}
>>>
>>> {k:dict1.get(k, [0, 0]) + dict2.get(k, [0, 0]) for k in dict1.viewkeys() | dict2.viewkeys()}
{'key2': [0, 0, 5, 6], 'key1': [1, 2, 3, 4]}

Upvotes: 2

Related Questions